“可能引发异常的验证” - 命名约定和语义

发布于 2024-10-10 13:38:46 字数 783 浏览 1 评论 0原文

如果您验证代码中的某些内容,您可以使用指示出现问题的返回值,或者可以抛出异常。在我的控制器中,我有这样的异常验证:

 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏末的微笑 2024-10-17 13:38:46

通常您会使用:

// for a validations that returns just plain yes no (true|false). in the case of a property use caching for the last validationresult.
bool IsValid

// for a validation that returns a list of errors of some sort (messagelist, id list, custom objects, whatever you need).
object Validate();

// validates and throws an exception if one or more error occured.
void ValidateAndThrow();

另外请务必考虑是否需要某种警告。例如,如果您验证注册 DTO 模型,并希望在密码较弱时警告用户,但又不想阻止用户保存密码(如果他选择这样做)。

Typically you would use:

// for a validations that returns just plain yes no (true|false). in the case of a property use caching for the last validationresult.
bool IsValid

// for a validation that returns a list of errors of some sort (messagelist, id list, custom objects, whatever you need).
object Validate();

// validates and throws an exception if one or more error occured.
void ValidateAndThrow();

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文