繁体   English   中英

“助手”类-如何更好地实施

[英]“Helper” Class - how to implement better

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

int start
int count

我们应该验证, start不少于0(应为0或更大), count应在0​​..999的范围内。 如果这两个参数有效,我们将继续执行我们的方法,否则将引发异常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并创建另一个名为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类是简单的Util类,它可以在项目周围包括许多这样的方法(validate,generate等)。

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

哪种方法更好? 还是其他方法?

奥列格(Oleg),我不确定您是否会抛出该特定异常,但您是否考虑过?:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM