Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should one comment an if-else structure? [duplicate]

People also ask

What is the replacement of if-else statement?

The Ternary Operator One of my favourite alternatives to if...else is the ternary operator. Here expressionIfTrue will be evaluated if condition evaluates to true ; otherwise expressionIfFalse will be evaluated. The beauty of ternary operators is they can be used on the right-hand side of an assignment.

How do you write the if-else condition?

Conditional Statements Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.

Can we use if statement twice?

Answer 514a8bea4a9e0e2522000cf1You can use multiple else if but each of them must have opening and closing curly braces {} . You can replace if with switch statement which is simpler but only for comparing same variable.


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;
}

Another option is:

if(condition) { //check for condition
    i = 1;
} else { //condition isn't met
    i = 2;
}

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 {
...
}

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.


Go for self-commenting conditions,then additional comments aren't necessary. Let's say the condition is that the maximum loan to value is reached. This gives us:

if (maximumLoanToValueIsReached)
{
   i=1;
}
else
{
   i=2;
}

No need to specify when i=2 that the maximum loan to value hasn't been reached as that is self explanitory. As an aside, I'd also rename i to something more meaningful.