vendredi 29 mai 2015

if and else if do the same thing

I'm trying to refactor an if-else chain that doesn't look particularly good. My common sense is telling me that I should be able to call my method only once but I can't figure out an elegant way to do it. Currently what I have is:

if(condition1)
  do method1;
else if(condition2)
  do method1;

Which looks hideous. There's repeat code! The best I can come up with is:

if(condition1 || (!condition1 && condition2))
  do method1;

But this also looks bad, since I'm negating condition1 after the or, which seems unnecessary...

I made a truth table for this thinking it was maybe the case for a specific operator like xor but I don't know of any operators that deal with this:

 c1| c2| r
 0 | 0 | 1
 0 | 1 | 1
 1 | 0 | 0
 1 | 1 | 1

And in case anyone is interested, the real-life problem I'm having is that I got 2 intances of Fancytree in javascript and I want to set some rules to transferring nodes between them. Tree A can only transfer lone nodes to Tree B, while Tree B can reorder itself freely, so I put this on Tree B's dragDrop event:

if(data.otherNode.tree === node.tree){ 
  data.otherNode.moveTo(node, data.hitMode);
}
else if(!data.otherNode.hasChildren()){
  data.otherNode.moveTo(node, data.hitMode);              
}

Aucun commentaire:

Enregistrer un commentaire