Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It's irrelevant if you're using ifs or different objects, the number of conditions/tests needed for what you are testing is the same.

Now, you could make depObj1 of type Obj1 and Obj2 to replace the if, which may simplify testing because the method is "simpler" in Obj1/Obj2/ObjBase but in the end it isn't!

Why? Because your test of Obj1/2 has to take care of their dependency to ObjBase. It's usually a dependency hell, needing lots of workarounds to test properly.



I might agree if that type of if statement only appeared at one point in the code, but there're normally several scattered around which all have to be updated when obj3 is introduced. Also introducing a class hierarchy often makes it easier to move responsibilities between objects as the code evolves.

For example I recently did some work on a graphics library which had a lot of ifs to do with line and fill styles. By changing those into an inheritance hierarchy I found a couple of places where clauses had been missed and so fixed some bugs, but more importantly when we needed to add new fill styles which were more complicated to draw it became very easy to turn the fill style objects into fillers which had all the responsibility for filling paths, not simply setting the graphics state.


Yes, there are situations where changing the structure of the code is better than having an 'if' like the example you gave.

But this doesn't mean that it's better to completely eliminate ifs




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: