“可能引发异常的验证” - 命名约定和语义
如果您验证代码中的某些内容,您可以使用指示出现问题的返回值,或者可以抛出异常。在我的控制器中,我有这样的异常验证:
void DoSomething()
{
Validate(); // throws exception if something is wrong
.....
}
我想知道是否有一个通用的命名约定,这意味着当出现问题时会抛出异常,这样我就不需要添加注释 // throws exception if something是错误的
并与if (!IsValid())
区别
注意:validation-naming-conventions 没有回答我的问题。
接受答案后更新:我从这个问题中学到了什么
- AssertValid()或VerifyAndThrow()是好名字(tnx @hacktick)
- 验证必须与上下文(警告或错误)区分开来
- 异常验证很好作为一种契约或第二道防线,可能只存在于调试模式下,以确保周围的
if (IsValid(...))
不会错过任何东西( tnx@科迪·格雷)
If you validate something in code you can either work with a return value indicating that something is wrong or you can throw an exception. In my controller I have Exceptional validation like this:
void DoSomething()
{
Validate(); // throws exception if something is wrong
.....
}
I wonder if there is a common naming convention that implies that an exception is thrown when something is wrong so that I don't need to add the comment // throws exception if something is wrong
and distinguishes from if (!IsValid())
Note: validation-naming-conventions does not answer my question.
Update after accepting the answer: What I have learned from this Question
- AssertValid() or VerifyAndThrow() are good names (tnx @hacktick)
- Validation must distinguish with a context (warning or error)
- Exceptional Validation is good as a kind of Contract or second line of defense that might exist only in Debug mode to ensure that the surrounding
if (IsValid(...))
does not miss something (tnx @ Cody Gray)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常您会使用:
另外请务必考虑是否需要某种警告。例如,如果您验证注册 DTO 模型,并希望在密码较弱时警告用户,但又不想阻止用户保存密码(如果他选择这样做)。
Typically you would use:
Also make sure to consider if you need warnings of some kind. For example if you validate your registration DTO model and want to warn a user if the password is weak but do not want to prevent the user from saving it if he chooses to.