验证命名约定? C#
非常简单的问题,但我想开始对验证方法使用一致的命名约定,但我想不出最好的方法!
人们倾向于使用 IsDataValid() 风格吗?或者还有其他更具描述性和意义的吗?
干杯
Very simple question, but I want to start using a consistent naming convention for validation methods and I can't think of the best way!
Do people tend to use IsDataValid() style? or are there any others that are more descriptive and meaningful?
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这取决于您的验证方法的作用。
如果它返回一个布尔值,那么可能以
Is
开头并以Valid
结尾是一个不错的起点。使用is
进行布尔调用通常会导致if
语句中的代码可读。如果您的验证方法引发异常,那么我通常会以
Check
之类的内容开始方法名称。然而,还值得考虑的是(因为方法通常应该使用动词)方法名称以
Validate
开头。Is
样式通常更适用于属性。It depends what your validation method does.
If it returns a Boolean, then probably starting with
Is
and ending withValid
is a good place to start. Usingis
for Boolean calls generally leads to readable code inif
statements.If your validation method throws an exception, then I'd usually start the method name with something like
Check
instead.However, also worth considering (as methods should usually use verbs) is beginning the method name with
Validate
. TheIs
style is generally more applicable to properties.与涉及命名约定的任何事情一样,不存在正确的答案,但是验证方法存在很多常见问题,这些问题适合某种方法,即:
我发现一种有用的方法是为我想要验证的每个模型对象提供一个单独的验证器类,该验证器类实现了通用的 IValidator 接口,通常使用以下方法:
这允许在您的业务逻辑中非常自然地使用:
As with anything involving naming conventions, there's no such thing as a right answer, but there's a lot of common problems with validation methods that lend themselves towards a certain approach, namely:
One approach I've found to be useful is to have a seperate validator class for each model object I want to validate that implements a common
IValidator
interface, usually with the following methods:This allows a pretty natural usage within your business logic:
当方法返回单个布尔值时,我通常使用“Is”MethodName 样式。就命名而言,这是完全可以接受的。很多时候,数据验证是在属性集而不是方法中完成的,因此在这种情况下,您不需要更改属性名称来指示它验证其上的数据集。
以下链接提供了一些您可能也会感兴趣的通用命名指南:
命名指南:
http://msdn.microsoft.com/en -us/library/xzf533w0(v=vs.71).aspx
I typically use the 'Is' MethodName style when the method returns a single Boolean value. It is perfectly acceptable in terms of naming. A lot of times data validation is done within the Set of a Property rather than a method so in this case you don't need to change the property name to indicate it validates the data set on it.
Here is a link that gives some general naming guidlines which you might find interesting as well:
Naming Guidelines:
http://msdn.microsoft.com/en-us/library/xzf533w0(v=vs.71).aspx