vendredi 26 février 2016

Good practice / design pattern to resolve the nested if else?

Currently I have a code like this:

for (each item) {
   if (item == 'x') { 
      print
   }
   if (item == 'y) {
      print
   } 
}

Now, I there is an additional requirement - I want the same checks but instead of printing, I need to insert in DB.

ie

for (each item) {
   if (item == 'x') { 
      insertDB
   }
   if (item == 'y) {
      insertDB
   } 
}

This has duplicated code, so flags come to my thought.

for (each item) {
   if (item == 'x') { 
      if (insertDB) {
          insertDB
      } else {
          print
      }
   }
   if (item == 'y) {
      if (insertDB) {
         insertDB
      } else {
         print
      }
   } 
}

This has clearly caused a lot of if-else clutter. My Object oriented programming tells me a new idea.

for (each item) {
   if (item == 'x') { 
      obj.doItemXAction();
   }
   if (item == 'y) {
      obj.doItemXAction();
   } 
}

Object obj = new PrintObj();
Object obj = new DBInsertObj();

Code looks much cleaner. But, given what I could think off, can anyone point me to exact design pattern which deals in situations like this ?

Aucun commentaire:

Enregistrer un commentaire