Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid if... else and switch cases

I have been programming for alot of time. Generally i program in some languages like PHP, ASP.net, Java, JavaScript and others. In all languages i have to use alot of if else statments . Like if value= 10 then ... if i review my code then i find alot of if conditions. So i would like to minimise them but how not sure.

one point was using classes somewhat minimised but still they are more...

like task, cat, sec and type:

if task = 'add' then
   if cat = "animal" then
      if sec = "man" then
          if type = "male" then
                 'do the following stuffs
          else
                 'do the following stuffs
          end if
      elseif sec = "horse" then
          if type = "run"
                 'do the following stuffs
          else
                 'do the following stuffs
          end if
      elseif....
      end if
   elseif cat = "plant" then
     if sec = "land" then
          if type="tree" then
                 'do the following stuffs
          elseif type = "grass" then..
                 'do the following stuffs
          elseif...
          end if
    elseif sec = "water" then
    ...
...

...

more n more continue n continue

so wonder how can i minimise them and write some efficient codes?

Sorry to inform lately that there may be alot of values for task, cat, sec, and type. My if statements are going nested n nested.

More explanatory my code also looks like same as :

http://thedailywtf.com/Articles/Coding-Like-the-Tour-de-France.aspx

like image 390
KoolKabin Avatar asked Aug 03 '10 06:08

KoolKabin


2 Answers

Many if..else statements is often a symptom the Polymorphism is not being used.

like image 134
Mitch Wheat Avatar answered Nov 15 '22 21:11

Mitch Wheat


It's called 'Arrow Antipattern' Some of the methods of dealing with it are described here: http://c2.com/cgi/wiki?ArrowAntiPattern

One of the ways you migt consider, is to refactor code in nested levels to separate functions like

if cat = "animal" then
  functionForAnimal();
elseif cat = "plant" then
 functionForPlant();
elseif...


function functionForAnimal() 
  if sec = "man" then
    functionForMan();
  elseif sec = "horse" then
    functionForHorse();
  elseif...

etc...

This splits code into smaller fragments which are easier to maintain, and possibly reusable.

like image 33
Mchl Avatar answered Nov 15 '22 21:11

Mchl