A related needless
if...
else that I frequently encounter in
computer programing code concerns the use of
Boolean variables. Many of us program in languages such as
Java,
C#,
Delphi and others where
boolean is a built-in
type that can only take the values
True and
False. Even those who program in
C/
C++ where a Boolean is just a disguised
integer may encounter the same needless else and can apply the same remedy.
To rework kaatunut's example using the boolean type, the needless else occurs in code such as
bool IsFive(int a)
{
if (a == 5)
return true;
else
return false;
}
The if statement in all these languages requires its test to be an expression that evaluates to a boolean. So this statement says roughly: "evaluate some boolean condition, and it is true, return true, else if it is false, return false." This can be expressed more simply as "evaluate some boolean condition, and return it". In code:
bool IsFive(int a)
{
return (a == 5);
}
Similarly you might see code in larger procedures which can be simplified, e.g.
...
if ((a == 5) && (b == 4))
IsFiveAndFour = true;
else
IsFiveAndFour = false;
...
Naturally, you will occasionally have to reverse the sense of your test, e.g.
bool IsNotFive(int a)
{
if (a == 5)
return false;
else
return true;
}
becomes
bool IsNotFive(int a)
{
return (a != 5);
}
In doing more complex sense-changing,
DeMorgan's Laws may be of use.
Here's a slightly more complex case taken from some Delphi code that I worked with, where the line count is reduced from 7 to 3.
if AnEngine.Error <> '' then
begin
ShowErrorMessage(AnEngine.Error);
Result := False;
end
else
Result := True;
becomes
Result := (AnEngine.Error = '');
if not Result then
ShowErrorMessage(AnEngine.Error);
Is the shorter version better code? In my opinion, yes. I do not care about saving a few bytes in the size of the source code - disk space is dirt cheap. Source code readability is a much more important goal, and concise code is readable. The effect on the resulting program is also important. While premature optimisation is a bad thing, coding in an efficient manner from the outset is a good idea.