Stop using if else statements

Conditions are a necessity to logic. You need them.

But the use of else drives me mad!

It’s code pollution. Not only does it look gross but it slows a developers ability to understand code.

Consider the following censored PHP code sample from a real web app:

if (stripos(getcwd(), "/some/deep/directory/") !== false)
{
	// Perform some action
	// Usually several lines of code
	$include_path = './' . PATH_SEPARATOR . get_include_path() . PATH_SEPARATOR . getcwd() . '/something/';
	set_include_path($include_path);
}
else
if (stripos(getcwd(), "/some/other/deep/directory/") !== false)
{
	// Perform some action
	// Usually several lines of code
	$include_path = './' . PATH_SEPARATOR . get_include_path() . PATH_SEPARATOR . getcwd() . '/something-else/';
	set_include_path($include_path);
}
else
{
	// Do your worst
	$include_path = './' . PATH_SEPARATOR . get_include_path() . PATH_SEPARATOR . getcwd() . '/default/';
	set_include_path($include_path);
}

Good lord what is happening here.

moss-throwing-monitor

Let’s say you are new to the code base and you are reading through this for the first time (you probably are). You would need to think about what would happen if you executed this code considering every step of the condition.

Stop making me think!

Now consider the following elseless code that does the exact same thing.

$root_path = './' . PATH_SEPARATOR . get_include_path() . PATH_SEPARATOR . getcwd();
$relative_include_dir = '/default/';

if (stripos(getcwd(), "/some/deep/directory/") !== false)
{
	// Perform some action
	// Usually several lines of code
	$relative_include_dir = '/something/';
}

if (stripos(getcwd(), "/some/other/deep/directory/") !== false)
{
	// Perform some action
	// Usually several lines of code
	$relative_include_dir = '/something-else/';
}

$include_path = $root_path . $relative_include_dir;

Much nicer.

Now we have default action that always happens and if either of the two separate conditionals that follow are true it will execute that as well. It is easy to follow. I can tell what is going to happen here without need to overthink or execute the script.

So do me a favour and stop using else!

Share Button

Tagged under:

0 comments
Back to top
http://twitter-widget.com/blog/button-html/