获取 StyleCop 规则 SA1503 CurlyBracketsMustNotBeOmit 更加灵活
我对 StyleCop 规则 SA1503 (CurlyBracketsMustNotBeOmited) 感到很困难。
在我的代码中,我经常有这样的模式:
public void SomeFunction(string someArg)
{
if (string.IsNullOrEmpty(someArg)) throw new ArgumentNullException("someArg");
// rest of the function here
}
其背后的基本原理是在对单个参数进行多次验证检查和/或对多个参数进行检查时节省垂直空间。 此类检查中的逻辑通常简单明了,抛出的异常也是如此。
但是,我永远不会写
if (someConditional)
DoSomeStuff();
我总是会写
if (someConditional)
{
DoSomeStuff();
}
所以总结一下:
- 如果 if 语句分成多行,请使用大括号
- 不要使用大括号进行简单的参数验证等,这很容易(并且可读)写一行
StyleCop 可以帮我吗?
I am having a hard time with StyleCop rule SA1503 (CurlyBracketsMustNotBeOmitted).
In my code I quite often have a pattern thus:
public void SomeFunction(string someArg)
{
if (string.IsNullOrEmpty(someArg)) throw new ArgumentNullException("someArg");
// rest of the function here
}
The rationale behind this is to save vertical space when doing multiple validation checks on a single argument and/or checks on many arguments. The logic in such a check is typically simple and concise and likewise for the exception that gets thrown.
However, I would never write
if (someConditional)
DoSomeStuff();
I would always write
if (someConditional)
{
DoSomeStuff();
}
So in summary:
- Use curly brackets if the if statement is split across multiple lines
- Don't use curly brackets for simple argument validation etc that can be easily (and readably) put on one line
Can StyleCop help me here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如已经提到的,不幸的是,StyleCop 规则要么打开,要么关闭,并且无法自定义。 如果有一种简单的方法来自定义规则就好了,但不幸的是您需要从头开始编写它们。
我使用 StyleCop 的方式是专注于使用尽可能多的内置规则,并且当我确实对规则有基本问题(例如代码文档)时,我只是将其关闭。 我不太关心例外情况,以至于无法编写自定义规则。
As already mentioned, unfortuntely StyleCop rules are either on or off and can't be customised. It would be nice to have a simple way of customising rules but unfortunately you'll need to write them from scratch.
The way I've used StyleCop is to focus on using as many of the built in rules as possible and where I really have a fundamental issue with a rule (code documentation, for example), I just turn it off. I'm not concerned enough about the exceptions to go to the extent of writing custom rules.
StyleCop(我同意)希望你将其分成多行。 它不喜欢一行中的 if 语句,(可以说)有充分的理由 - 这会导致 if 语句的使用模式不一致,这也是规则存在的首要原因之一。
为了获得您所显示的行为,您可能需要使用 SDK 为特定情况编写自己的自定义规则,然后禁用默认规则。
StyleCop (and I agree here) wants you to split this into multiple lines. It doesn't like if statements on one line, for (arguably) good reason - this causes an inconsistent usage pattern for if statements, which is one of the reasons that rule exists in the first place.
To get the behavior you're showing, you'd likely need to use the SDK to write your own customized rule for that specific case, and then disable the default rule.