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

Wait, what's wrong with if-statements? I apparently missed the boat on that one.


It really depends. Sometimes people try to stuff way too much strategy-picking in if-conditions when they ought to delegate the behavior to some strategy-objects instead, where each code path could be better understood and tested in isolation. (Subclassing can also work here but it’s less flexible.)

I also particularly dislike it when you’re trying to support two different formats of payload in the same API, and if() based on presence of the new field. Expedient, I’ll grant, but if not reversed quickly it’s soon absolutely unintelligible. The more-stable systems which have to support clients sending older formats do better by versioning the format, and just having multiple implementations doing whole-payload validation, and delegating to the same underlying task-object (you do have one of those outside the class that’s just about interfacing with HTTP, right? ... okay that’s fine, I understand, but you’re gonna do it now.)

On the other hand, sometimes an if-statement is the logic itself. That’s fine.


A lot of it's down to a paradigm conflict. In general, if statements are fine. But they're not really considered to be object-oriented. Smalltalk technically doesn't even have an if statement.

I will say that, when I see object-oriented code that branches on the particular subclass of a value at run time, it's often one of the earlier sign that the code is getting messy. Subclassing is supposed to be used for a "don't ask, tell" style of programming. A lot of the problems with OOP that people like to complain about aren't really problems with object-oriented programming, per se; they're problems that crop up when object-oriented and procedural programming are mixed in an uncontrolled manner.


>will say that, when I see object-oriented code that branches on the particular subclass of a value at run time, it's often one of the earlier sign that the code is getting messy.

Suppose you have AST which has Node and its various subclasses like ExpressionNode, which then has e.g ConstantExpressionNoee

And so on, many, many other

How would you then avoid branching basing on type?




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

Search: