"Helper" Class - 如何更好地实施

"Helper" Class - how to implement better

例如,我的 class 方法应该在使用前验证输入值。建议,方法的2个参数是:

int start
int count

我们应该验证,start 不小于 0(应该是 0 或更大),count 应该在 0..999 范围内。如果这 2 个参数有效,我们继续执行我们的方法,否则抛出异常 BillComInvalidRangeException:

public class BillComInvalidRangeException : Exception
{
    const string invalidRangeMessage = "The range is not valid. 'Start' should be greater than 0, 'Count' in range 0..999.";

    public BillComInvalidRangeException(int start, int count) : base($"{invalidRangeMessage} Passed 'Start' : {start}, 'Count' : {count}")
    {
    }
}

我想按照 SRP 再创建一个 class,命名为 ValidateListRange。我可以通过 3 种方法实现它:

  1. 验证方法中的值:

    public bool Validate(int start, int count)
    {
        return !(start < 0
        || count < 0
        || count > 999);
    }
    

然后只是为了使用:

var validateObject = new ValidateListRange();
if (!validateObject.Validate(start, count))
    throw new BillComInvalidRangeException(start, count);
  1. 在静态方法中验证值:

    public static bool Validate(int start, int count)
    {
        return !(start < 0
            || count < 0
            || count > 999);
    }
    

然后使用:

        if (!ValidateListRange.Validate(start, count))
            throw new BillComInvalidRangeException(start, count);

具有相同功能的更短的记录。然后我们的 ValidateListRange class 是简单的 Util class,它可以包含项目周围的许多方法(验证,生成等)。

但是使用非静态 class 我们有一个巨大的好处 - 我们可以使用接口,然后传递必要的验证对象而无需更改我们的项目源代码。例如,将来我们应该验证 9999,而不是 999,我们可以编写一个新的 ValidateListRange class 实现。如果有必要

哪种方法更好?或者任何其他方法?

Oleg,我不确定你在抛出那个特定异常时有多难,但你有没有考虑过?:

  1. FluentValidation (https://www.nuget.org/packages/fluentvalidation)

  2. 代码合同 (https://docs.microsoft.com/en-us/dotnet/framework/debug-trace-profile/code-contracts)