My question might get closed, but I'm curious about whether it's always required to add an "else" part to every "if" statement in coding. A senior programmer told me, "You should always have an 'else' part in every 'if' statement." However, what should we do if there's no reason to include an "else" part? I think this could lead to an interesting discussion.
That's a horrible idea. You end up with code of the form:
if (something) {
doSomething();
} else {
}
How anyone could think that's more readable or maintainable that not having an else
at all is beyond me. It sounds like one of those rules made up by people who have too much free time on their hands. Get them fired as quickly as you can, or at least move away calmly and quietly :-)
"One option is to code the else clause—with a null statement if necessary—to show that the else case has been considered. Coding null elses just to show that that case has been considered might be overkill, but at the very least, take the else case into account. When you have an if test without an else, unless the reason is obvious, use comments to explain why the else clause isn’t necessary." - Code Complete
I feel conflicted, what do you think ? –
Contrasty if
statement, consider whether you don't actually need an if-then-else
statement." Every bit of code I write is the result of informed consideration like that: nn this case, rejected since a decent programmer will know that a missing else
clause means no action should be taken. I don't read a function and wonder about the seven lines that were never placed at the end of it, that's exactly the attitude you should take to the missing else
:-) –
Pirog you should avoid 'if-then-else' statements where the 'if' block has no statements in its body and instead negate the test condition
(I am paraphrasing). –
Contrasty if
condition without an else
clause. "If condition is not met, nothing will happen" is just wrong in many cases. You can always add an exception or a log entry to the else
clause. –
Refractory else
block is needed but don't put in empty ones for no value. –
Pirog No, you certainly don't have to - at least in most languages. (You didn't specify; it's quite possible that there's a language which does enforce this.) Here's an example where I certainly wouldn't:
public void DoSomething(string text)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
// Do stuff
}
Now you could put the main work of the method into an "else" clause here - but it would increase nesting unnecessarily. Add a few more conditions and the whole thing becomes an unreadable mess.
This pattern of "early out" is reasonably common, in my experience - and goes for return values as well as exceptions. I know there are some who favour a single return point from a method, but in the languages I work with (Java, C#) that can often lead to significantly less readable code and deeper nesting.
Now, there's one situation where there's more scope for debate, and that's where both branches are terminal, but neither of them is effectively a shortcut:
public int DoSomething()
{
// Do some work
if (conditionBasedOnPreviousWork)
{
log.Info("Condition met; returning discount");
return discount;
}
else
{
log.Info("Condition not met; returning original price");
return originalPrice;
}
}
(Note that I've deliberately given both branches more work to do than just returning - otherwise a conditional statement would be appropriate.)
Would this be more readable without the "else"? That's really a matter of personal choice, and I'm not going to claim I'm always consistent. Having both branches equally indented gives them equal weight somehow - and perhaps encourages the possibility of refactoring later by reversing the condition... whereas if we had just dropped through to the "return original price", the refactoring of putting that into an if block and moving the discount case out of an if block would be less obviously correct at first glance.
In imperative languages like Java and C, if - else
is a statement and does not return a value. So you can happily write only the if
part and go on. And I think that it is the better practice rather than adding empty else
s after every if
.
However in functional languages like Haskell and Clojure, if
is an expression and it must return a value. So it must be succeeded with an else
. However there are still cases where you may not need an else
section. Clojure, for such cases, has a when
macro which wraps if - else
to return nil
in the else
section and avoid writing it.
(when (met? somecondition)
(dosomething))
if-else
expression. –
Filamentary Danger! Danger, Will Robinson!
http://en.wikipedia.org/wiki/Cargo_cult_programming
Is the inclusion of empty else { }
blocks going to somehow improve the quality, readability, or robustness of your code? I think not.
Looking at this purely from a semantic point of view - I cannot think of a single case where there is not an implicit else for every if.
if the car is not stopped before I reach the wall I will crash, else I will not crash.
Semantics aside:
The answer to that question depends on the environment, and what the result of a mistake is.
Business code? Do what your coding standards say.
IMHO you will find that spelling it out, although initially it seems like too much work, will become invaluable 10 years from now when you revisit that code. But, it certainly would not be the end of the world if you missed an important 'anti-condition'.
However: Security, Safety or Life Critical code? That's a different story.
In this case you want to do two things.
First:Rather than testing for a fault, you want to prove there is not a fault. This requires a pessimistic view on entry to any module. You assume everything is wrong
until you prove it is correct.
Second: in life critical: You NEVER want to hurt a patient.:
bool everyThingIsSafe = true;
if(darnThereIsAProblem())
{
reportToUserEndOfWorld();
}
return everyThingIsSafe;
Oops. I forgot to set everyThingIsSafe false.
The routine that called this snippit is now lied to. Had I initialized evertThingIsSafe to false - I'm always safe, but now I need the else clause to indicate that there wasn't an error.
And yes, I could have changed this to a positive test - but then I need the else
to handle the fault.
And yes, I could have assigned everyThingIsSafe() the immediate return of the check.
And then tested the flag to report a problem. An implicit else, why not be explicit?
Strictly speaking, the implicit else this represents is reasonable.
To an FDA/safety auditor, maybe not.
If it's explicit, can point to the test, its else, and that I handled both conditions clearly.
I've been coding for medical devices for 25 years. In this case, you want the else, you want the default in the case, and they are never empty. You want to know exactly what is going to happen, or as near as you can. Because overlooking a condition could kill someone.
Look up Therac-25. 8 severely injured. 3 dead.
I know I am late but I did a lot of thinking over this and wanted to share my results.
In critical code, it is imperative for every branch is accounted for. Writing an else is not necessary, but leave a mark that else is not necessary and why. This will help the reviewer. Observe:
//negatives should be fixed
if(a < 0) {
a+=m;
}
//else value is positive
No, It's not required to write the else
part for the if
statement.
In fact most of the developers prefer and recommend to avoid the else
block.
that is
Instead of writing
if (number >= 18) {
let allow_user = true;
} else {
let allow_user = false;
}
Most of the developers prefer:
let allow_user = false;
if (number >= 18) {
let allow_user = true;
}
No, you don't have to ..
Also, I don't think that it is a good idea for readability, since you will have lots of empty else blocks. which will not be pretty to see.
No, but I personally choose to always include encapsulating braces to avoid
if (someCondition)
bar();
notbar(); //won't be run conditionally, though it looks like it might
foo();
I'd write
if (someCondition){
bar();
notbar(); //will be run
}
foo();
Sometimes there is no else part....and including an empty one just makes the code less readable imho.
This is purely a matter of style and clarity. It's easy to imagine if statements, particularly simple ones, for which an else would be quite superfluous. But when you have a more complex conditional, perhaps handling a number of various cases, it can often be clarifying to explicitly declare that otherwise, nothing ought to be done. In these cases, I'd leave a // do nothing
comment in the otherwise empty else to it clear that the space is intentionally left blank.
def in_num(num):
if num % 3 == 0:
print("fizz")
if num % 5 == 0:
print("buzz")
if (num % 3 !=0) and (num % 5 !=0):
print(num)
see in this code else statement is not necessary.
© 2022 - 2024 — McMap. All rights reserved.