How should one comment an if-else structure?
Solution 1
If it is needed to comment if else statements, I prefer to describe the case what made the code reach that point. Especially in code with a high cyclomatic complexity
if (condition) {
// User is taking a course at college x:
i = 1;
} else {
// User is not taking any course at college x:
i = 2;
}
Solution 2
Another option is:
if(condition) { //check for condition
i = 1;
} else { //condition isn't met
i = 2;
}
Solution 3
You should only only annotate if the code is not self explanatory. So make the if self explanatory. Like this perhaps
bool fooIsNotReallyGood = ....;
if(fooIsNotReallyGood) {
...
} else {
...
}
Solution 4
If the code is not already self-documenting, then I would structure it as follows:
if (someCondition) {
// If some condition, then do stuff 1.
doStuff1();
}
else {
// Else do stuff 2.
doStuff2();
}
But again, it doesn't make much sense if the code is already self-documenting. If you would like to add comments because of some complex condition like:
if (x == null || x.startsWith("foo") || x.endsWith("bar") || x.equals("baz")) {
doStuff1();
}
else {
doStuff2();
}
Then I would consider to refactor it as:
boolean someCondition = (x == null || x.startsWith("foo") || x.endsWith("baz") || x.equals("waa");
if (someCondition) {
doStuff1();
} else {
doStuff2();
}
Wherein the variable name someCondition
actually summarizes the whole condition in a nutshell. E.g. usernameIsValid
, userIsAllowedToLogin
or so.
Solution 5
Comments are very much a personal thing, and (as can be seen by some of the earlier answers) generate as much debate as the code.
In simple cases, comments detract from the code. But assuming a more complex condition, I prefer:
/*
** 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();
}
In any case, the comments must not just repeat the code.
user2012801
Open source projects: Java HTML compressor/minifier jQuery loading mask plugin Chrome extensions: A whole bunch Feel free to contact me at: [email protected]
Updated on July 05, 2022Comments
-
user2012801 almost 2 years
Lets say you have:
if(condition) { i = 1; } else { i = 2; }
and you need to put comments explaining
if
andelse
blocks. What's the most readable way of doing it so someone can easily pick them up at first glance?I usually do it like this:
//check for condition if(condition) { i = 1; } else { //condition isn't met i = 2; }
which I find not good enough as comments are located at different levels, so at quick glance you would just pick up
if
comment andelse
comment would look like it belongs to some inner structure.Putting them like this:
if(condition) { //check for condition i = 1; } else { //condition isn't met i = 2; }
doesn't look good to me either as it would seem like the whole structure is not commented (condition might be big and take multiple lines).
Something like that:
//check for condition if(condition) { i = 1; //condition isn't met } else { i = 2; }
would be probably the best style from comments point of view but confusing as a code structure.
How do you comment such blocks?
PS. I am not asking about refactoring this two lines of code, only about code style and comment formatting.
-
mpen about 14 yearsthis is the option I like... unless the comments are really long, then you're screwed...... i get frustrated and delete the comments because the look ugly.
-
Aoi Karasu about 14 yearsLol, in such case isn't it better to do something like this? if (condition) conditionIsMet(); else conditionIsNotMet();
-
David Johnstone about 14 years+1 I do my best to have my code understandable without comments
-
helpermethod about 14 years+1 Best solution in my opinion.
-
Faken about 14 yearsI like this method of doing things. It may take up more space but it makes it absolutely clear what is covered in a loop/if statement.
-
drawnonward about 14 yearsThis is what I do. If the comments are long then put a comment block above the conditional explaining the whole thing.
-
user2012801 about 14 yearsI like all comments start at the same position (at top level preferably). Having them all over the place is much harder to read to me.
-
user2012801 about 14 yearsThanks, but it is not what question is about.
-
Mike Burton about 14 years@serg555: You may not explicitly ask this question, but this is the answer all the same. If you were using actual comments in your examples above, it would immediately be clear that it depends completely on what the specific comment related to. An actual comment at the outer level, for example, might explain that when you have a particular graphics card installed a bug arises that is otherwise not a problem, so you do things differently based on that condition. An inner comment might explain a particularly complex algorithm and how it's tied to that particular branch of the if statement.
-
mmc over 11 yearsThis is fine in an ideal world of simple code. However, if the first block is long, it might no longer be as clear what the "else" block refers to (also in the case of nested ifs). He might also be cleaning up someone else's code that he'd rather not refactor. It's a perfectly legitimate question.
-
mmc over 11 yearsI like this... specifically the comment in the "else" block. Your condition should be clear, but depending on the length and complexity (especially nesting) of the code, the meaning of the "else" may not be obvious at all.
-
Preet Sangha over 11 years@mmc - that's what I added the bool variable. All tests can be reduced to to a single variable. If you need multiple variables to reduce the test to improve readability and so be it. This works in all cases. If you think that some code is too complex then you should be able create a simple expression and it only needs to be done once to ensure that future readers can see how the test works. Also I cannot imagine any piece of code where you can't simplify the code. If the simplification results in performance issues - that's when you introduce complex code with copious comments.
-
Andrew over 11 yearsTo me, "Check for condition" isn't helpful, either in its own right or as a generic place-holder. Comments MUST be helpful, and not just repeat the code, hence my preference (detailed below) of "Comment explaining what the condition is trying to determine"
-
s3m3n about 11 yearsI also prefer comment above else on the same tab level. I don't agree with not commenting code, if statement might be easy as
someCondition
, but inside its structure there are for example 300 lines and in this case NOT commenting else statement would be stupid, because you need to scroll 300 lines top and another 300 bottom.. -
Jonathan Potter about 9 yearsThis is a useful technique but it definitely does not eliminate the need for if/else comments in all situations.
-
aandis almost 9 yearsThis wouldn't work if for example, you wanted to put some comment for
i = 2
as well inside the else block. It would look like both of them are fori = 2
or both are for theelse
block. -
Daniel Saner almost 6 yearsThere are many problems with this code. First, the "either/or" relationship between your two functions (the fact that always only one of them will take effect) is obscured in
main()
. You have to look up the actual statements in several places, and don't immediately see if there could be any side effects. You're also checking the condition twice, which is potentially expensive. And it adds the overhead of two function calls, which will probably also want to return something back tomain
. — I know the answer is old, but thought it couldn't hurt to back up the downvotes in some way. -
Daniel Saner almost 6 years@aandis You could indent the comment relating to
i = 2;
to differentiate. Although I think that in any real-world situation, the comment itself should leave little doubt about whether it refers to the condition or the first statement. -
Guimo almost 5 years@aandis Or for that case you could put two comments separated by a single line. Vertical space should not be a problem since long or unclear methods should be refactored into smaller/clearer ones.