int IsFive(int a)
{
	if (a==5)
		return 1;
	else	/* the infamous 'needless else' */
		return 0;
}

The above C code demonstrates completely redundant use of a language directive, effectively increasing the size of source by 5+(indent_tab ? (root_column/tab_size) : root_column)+(is_dos_textfile==1) bytes (not including the comment above). On GCC, it doesn't produce larger binary, but you can't count on that.

The above code may appear to contain a "needless else," but that is only because the example is very small. Functions (or subroutines, whatever your language of choice calls them) should, as a general rule, have only one return statement, if any. This ensures that the function can be traced from beginning to end. I propose that the code be changed thusly:

int IsFive(int a) {
    int result;

    if(a == 5) {
        result = 1;
    } else {
        result = 0;
    }

    return result;
}

Admittedly, this version is longer, but there is a defined entrance point (which was never really an issue) and a single, defined exit point. This example is fairly trivial, but imagine working on a significantly larger program, written with brevity and minute savings in binary size in mind.

There are exceptions to every rule, however. File opening comes to mind for multiple exit points ( open(IN, $ARGV[0]) or die; ), and StrawberryFrog points out that error codes are much easier to deal with when using multiple return points. On the average, having one exit point makes for code that is easier to follow and debug. This holds especially true for students learning both a new language and how to program in general.

In the world of computing today, this should be a non-issue. Memory and processor cycles are both abundant the majority of the time. Write for clarity and readability unless you're genuinely working with excruciatingly tight memory constraints (e.g., an embedded system) or dealing with a special case. It'll save the next person to work on your code many headaches.

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.

Log in or registerto write something here or to contact authors.