ser*_*erg 66 comments coding-style
让我们说你有:
if(condition) {
i = 1;
} else {
i = 2;
}
Run Code Online (Sandbox Code Playgroud)
你需要发表评论解释if和else阻止.什么是最易读的方式,所以有人可以在第一眼就轻松拿起它们?
我通常这样做:
//check for condition
if(condition) {
i = 1;
} else {
//condition isn't met
i = 2;
}
Run Code Online (Sandbox Code Playgroud)
由于评论位于不同的级别,我觉得不够好,所以快速浏览一下你就会发现if评论和else评论看起来像是属于某种内部结构.
把它们像这样:
if(condition) {
//check for condition
i = 1;
} else {
//condition isn't met
i = 2;
}
Run Code Online (Sandbox Code Playgroud)
对我来说也不好看,因为看起来整个结构都没有评论(条件可能很大并且需要多行).
像这样的东西:
//check for condition
if(condition) {
i = 1;
//condition isn't met
} else {
i = 2;
}
Run Code Online (Sandbox Code Playgroud)
从评论的角度来看可能是最好的风格,但作为代码结构令人困惑.
你如何评论这些块?
PS.我不是要求重构这两行代码,只是关于代码样式和注释格式.
小智 31
如果需要评论if else语句,我更喜欢描述使代码达到这一点的情况.特别是在具有高圈复杂度的代码中
if (condition) {
// User is taking a course at college x:
i = 1;
} else {
// User is not taking any course at college x:
i = 2;
}
Run Code Online (Sandbox Code Playgroud)
Dav*_*one 23
另一种选择是:
if(condition) { //check for condition
i = 1;
} else { //condition isn't met
i = 2;
}
Run Code Online (Sandbox Code Playgroud)
Pre*_*gha 13
您应该只注释代码是否不自我解释.所以,如果自我解释.或许这样
bool fooIsNotReallyGood = ....;
if(fooIsNotReallyGood) {
...
} else {
...
}
Run Code Online (Sandbox Code Playgroud)
Bal*_*usC 10
如果代码还没有自我记录,那么我将按如下方式构造它:
if (someCondition) {
// If some condition, then do stuff 1.
doStuff1();
}
else {
// Else do stuff 2.
doStuff2();
}
Run Code Online (Sandbox Code Playgroud)
但同样,如果代码已经自我记录,则没有多大意义.如果你想添加评论,因为一些复杂的条件,如:
if (x == null || x.startsWith("foo") || x.endsWith("bar") || x.equals("baz")) {
doStuff1();
}
else {
doStuff2();
}
Run Code Online (Sandbox Code Playgroud)
然后我会考虑将其重构为:
boolean someCondition = (x == null || x.startsWith("foo") || x.endsWith("baz") || x.equals("waa");
if (someCondition) {
doStuff1();
} else {
doStuff2();
}
Run Code Online (Sandbox Code Playgroud)
其中变量名someCondition 实际上总结了整个条件.例如usernameIsValid, userIsAllowedToLogin左右.
去自我评论条件,然后不需要额外的评论.假设条件是达到最大贷款价值.这给了我们:
if (maximumLoanToValueIsReached)
{
i=1;
}
else
{
i=2;
}
Run Code Online (Sandbox Code Playgroud)
无需在i = 2时指定尚未达到最大贷款价值,因为这是自我解释.顺便说一句,我也会重命名i为更有意义的东西.
评论在很大程度上是一件很私人的事情,并且(从一些早期的答案中可以看出)和代码一样会引起很多争论。
在简单的情况下,注释会减损代码。但假设一个更复杂的条件,我更喜欢:
/*
** Comment explaining what the condition
** is trying to determine
*/
if ( condition )
{
/*
** Comment explaining the implications
** of the condition being met
*/
do_something();
}
else
{
/*
** Comment explaining the implications
** of the condition not being met
*/
do_something_else();
}
Run Code Online (Sandbox Code Playgroud)
无论如何,注释不能只是重复代码。
我根本不会在这些特殊情况下发表评论——这些评论不会给你已经清晰的代码增加任何价值。如果您有一个非常复杂且难以阅读的条件,我会考虑将其分解为一个inline具有自己的非常干净的名称的函数(可能)。
| 归档时间: |
|
| 查看次数: |
23891 次 |
| 最近记录: |