[TIDY UP YOUR CODE] :: if – elseif – elseif – elseif – else

I thought about doing an extra section called ‘TIDY UP YOUR CODE’.
From time to time I will post some tips how you can write reader-friendly code.
So Let’ start with the first topic: if – elseif – elseif – elseif – else

Have you ever seen something like this ?

if(expressionA)
{
  .. do something ..
}
elseif(expressionB)
{
  .. do something else..
}
elseif(expressionC)
{
  .. do something else..
}
elseif(expressionD)
{
  .. do something else..
}
else
{
  .. do something else..
}

Code like this is hard to read, don’t you agree with this?
TIDY IT UP! Use a switch instead:

switch(true)
{
  case expressionA:
  {
	.. do something ..
  }; break;
 
  case expressionB:
  {
	.. do something else ..
  }; break;
 
  case expressionC:
  {
	.. do something else ..
  }; break;
 
  case expressionD:
  {
	.. do something else ..
  }; break;
 
  default:
  {
	.. do something else ..
  }; break;
}

In my opinion this is great :-}

Comments (0)

› No comments yet.

Leave a Reply

Allowed Tags - You may use these HTML tags and attributes in your comment.

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Pingbacks (0)

› No pingbacks yet.