如何避免参数验证 [英] How to avoid argument validation

查看:202
本文介绍了如何避免参数验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

验证参数

当编写一个方法,争论应该先执行任何操作之前验证。例如,假设我们已经有了代表人民的类:

When writing a method, arguments should be validated first before any operations are performed. For example, let's say we've got a class representing people:

public class Person
{
    public readonly string Name;
    public readonly int Age;

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

什么不对的Person类?名字和年龄在他们的值设置为Person的字段不验证。我所说的意思是验证?这两种说法应检查它们的值是可以接受的。例如,如果name的值是什么一个空字符串?或年龄的值是-10?

What's wrong with this Person class? name and age aren't validated before their values are set as fields of Person. What do I mean by "validated?" Both argument should be checked that their values are acceptable. For example, what if name's value is an empty string? Or age's value is -10?

验证的参数是通过抛出ArgumentExceptions或派生的异常时的值是不可接受的执行。例如:

Validating the arguments is performed by throwing ArgumentExceptions or derived exceptions when the values are unacceptable. For example:

public class Person(string name, int age)
{
    if (String.IsNullOrEmpty(name))
    {
    	throw new ArgumentNullException
    		("name", "Cannot be null or empty.");
    }

    if (age <= 0 || age > 120)
    {
    	throw new ArgumentOutOfRangeException
    		("age", "Must be greater than 0 and less than 120.");
    }

    this.Name = name;
    this.Age = age;
}

这正确地验证人的构造函数接受的参数。

This properly validates the arguments Person's constructor receives.

乏味广告nauseum

由于您已经验证的参数很长时间(吧?),你可能厌倦了你的所有方法,写这些,如果(....)抛出参数...语句。

Because you've been validating arguments for a long time (right?), you're probably tired of writing these if (....) throw Argument... statements in all of your methods.

推荐答案

您可以看看在.NET 4.0中代码契约一>

You can look into Code Contracts in .NET 4.0.

您可能也想看看 FluentValidation图书馆在CodePlex上的,如果你不希望等待码合约

You may also want to look at the FluentValidation Library on CodePlex if you don't want to wait for code contracts.

最后,你还是需要把支配参数值某处的规则 - 它。早晚的事情决定你是否喜欢命令式的风格(如string.IsNullOrEmpty)或者声明一个

Ultimately, you still need to put the rules that govern argument values somewhere - it just a matter of deciding whether you prefer an imperative style (e.g. string.IsNullOrEmpty) or a declarative one.

验证您的输入,是编写可靠的代码的主要做法 - 但它肯定可以重复的,繁琐。

Validating your inputs as is a key practice for writing solid code - but it certainly can be repetitive and verbose.

这篇关于如何避免参数验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆