zoukankan      html  css  js  c++  java
  • Java和C#下的参数验证

    参数的输入和验证问题是开发时经常遇到的,一般的验证方法如下:

    public bool Register(string name, int age)
    {
        if (string.IsNullOrEmpty(name))
        {
            throw new ArgumentException("name should not be empty", "name");
        }
        if (age < 10 || age > 70)
        {
            throw new ArgumentException("the age must between 10 and 70","age");
        }
        //...
    }

    这样做当需求变动的时候,要改动的代码相应的也比较多,这样比较麻烦,最近接触到了Java和C#下2种方便的参数验证方法,简单的介绍下。

    Java参数验证:

    采用google的guava下的一个辅助类:

    import com.google.common.base.Preconditions;

    示例代码:

        public static void checkPersonInfo(int age, String name){
            Preconditions.checkNotNull(name, "name为null");
            Preconditions.checkArgument(name.length() > 0, "name的长度要大于0");
            Preconditions.checkArgument(age > 0, "age必须大于0");
            System.out.println("a person age: " + age + ", name: " + name);
        }
        
        public static void getPostCode(String code){
            Preconditions.checkArgument(checkPostCode(code),"邮政编码不符合要求");
            System.out.println(code);
        }
    
        public static void main(String[] args) {
            try {
                checkPersonInfo(10,"fdsfsd");
                checkPersonInfo(10,null);
                checkPersonInfo(-10,"fdsfsd");
                getPostCode("012234");
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    当参数不满足要求的时候,抛出异常信息,异常中携带的信息为后面自定义的字符串,这样写就方便多了。

    C#参数验证:

    采用FluentValidation这个类库,参考地址在下面。

    使用方法:

    一个简单的Person类:

        public class Person
        {
            public string Name { set; get; }
    
            public int Age { set; get; }
    
            public Person(string name, int age)
            {
                Name = name;
                Age = age;
            }
        }

    Person的验证类:

        public class PersonValidator : AbstractValidator<Person>
        {
            public PersonValidator()
            {
                RuleFor(x => x.Name).NotEmpty().WithMessage("姓名不能为空");
                RuleFor(x => x.Name).Length(1,50).WithMessage("姓名字符不能超过50");            
                RuleFor(x => x.Age).GreaterThan(0).WithMessage("年龄必须要大于0");
            }
    
            private bool ValidName(string name)
            {
                // custom name validating logic goes here
                return true;
            }
        }

    使用:

        class Program
        {
            static void Main(string[] args)
            {
                Person customer = new Person(null,-10);
                PersonValidator validator = new PersonValidator();
                ValidationResult results = validator.Validate(customer);
    
                bool validationSucceeded = results.IsValid;
                IList<ValidationFailure> failures = results.Errors;
                foreach (var failure in failures)
                {
                    Console.WriteLine(failure.ErrorMessage);
                }
    
                Console.ReadKey();
            }
        }

    FluentValidation的使用文档:http://fluentvalidation.codeplex.com/documentation

    参考资料:

    http://fluentvalidation.codeplex.com/

    https://github.com/JeremySkinner/FluentValidation

  • 相关阅读:
    ASP.Net请求小周期
    创建型设计模式
    eml文件解析实例,简历信息抓取工具
    Microsoft ReportViewer 控件类型版本兼容问题及解决方法
    WCF IIS 部署错误处理
    如何使Wpf浏览器应用程序被完全信任运行
    Server 2008 r2 多用户远程桌面配置
    The configuration section 'system.serviceModel' cannot be read because it is missing a section decla
    spss C# 二次开发 学习笔记(六)——Spss统计结果的输出
    spss C# 二次开发 学习笔记(二)——Spss以及统计术语解释(IT人眼中的统计术语)
  • 原文地址:https://www.cnblogs.com/luxiaoxun/p/4172776.html
Copyright © 2011-2022 走看看