Everything2
Near Matches
Ignore Exact
Full Text
Everything2

the infamous 'needless else'

created by kaatunut

(idea) by kaatunut (6.7 y) (print)   ?   (I like it!) Mon Jul 10 2000 at 15:39:03

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.

(idea) by jclast (9.1 mon) (print)   ?   (I like it!) Tue Mar 01 2005 at 19:55:41

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.


(idea) by StrawberryFrog (7.1 hr) (print)   ?   (I like it!) Tue Apr 05 2005 at 14:11:47

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.


printable version
chaos

How to say "else if" John and Eliza in the desert in love DeMorgan's Laws dangling else
GCC Learn to Program: If/Then Readability C
code One Hit Wonder Embedded system languages of choice
boolean ternary operator if statement John Paul II
Concise Stager Module clarity
return Subroutine function Java
Y'know, if you log in, you can write something here, or contact authors directly on the site. Create a New User if you don't already have an account.
  Epicenter
Login
Password

password reminder
register

Everything2 Help

Cool Staff Picks
Just another sprinkling of indeterminacy
I had forgotten the bear's name, and could not find my way home to the Thousand Acre wood
I can't live without you
chatterbox client
Bozo the Clown
Dutch
work
George W. Bush's address to the UN General Assembly: September 12, 2002
Body Ritual Among the Nacirema
Battle of Trafalgar
Richard Burton
Grethesis
Galapagos Hawk
kouprey
New Writeups
SubSane
Making Love to a 9-Foot Woman(person)
Ouzo
Thoughts(idea)
antigravpussy
I fall silent, listening. The breadcrumbs are talking about us(person)
calgon
Buffalo Bill by the pool(poetry)
gate
Anarchy is Order(idea)
ushdfgakjasgh
Scribeling(thing)
XWiz
Trism(review)
artman2003
Briefcase Full of Souls - Part I(fiction)
Dreamvirus
Alan Ladd(person)
waverider37
Harold Holt(person)
The Debutante
Until death do us part(fiction)
Ysardo
a brother to a sister(personal)
antigravpussy
your warm whispers(personal)
Clarke
Multiculturalism(idea)
aneurin
Earl of Landaff(person)
E2 is a by-product of the existence of The Everything Development Company