4 ms·
Agreed. You still need a nest of conditionals when you populate the tree, and you need a separate class for each operations - so what's the advantage of using p
by xsmasher 17y ago
Agreed. You still need a nest of conditionals when you populate the tree, and you need a separate class for each operations - so what's the advantage of using polymorphism here?
The disadvantage of poly here is more code and more classes. Yes, you can add a new operator without modifying the node class - but now you must modify the tree-populating code instead.
- Nycto 17y agoConsider a few of the benefits not mentioned in the article: - You have reduced the cyclomatic complexity of each class, which makes the code less fragile and easier to unit test. - When adding a new operator, you are now forced to implement everything it needs to work. If you don't define a method, it won't compile. This is not the case with a long list of if/else statements. - "You still need a nest of conditionals when you populate the tree..." This is true, but now all the conditionals are in one place, rather than two (in their example, toString and evaluate). Again, this will make testing easier.
- scott_s 17y agoYour second point is actually a feature, and is equivalent to structural pattern matching in languages with algebraic types not allowing you to have unspecified cases.
- jrockway 17y agoI think he was advertising this as a feature. Failing to compile is much better than hitting your "this can't happen" conditional at runtime.
- scott_s 17y agoYou're right, I didn't understand his intentions.
- wlievens 17y agoAbsolutely. One of the advantages of static typing (NOT starting a type war here, oh gods) is that you can transform error conditions from the run-time to the compile-time world. Earlier failure = cheaper failure, so this is great. I try to take this as far as I can. For instance, when writing Servlet code in Java, I define all my request parameter names in an enum, so that I can never misspell any lest the compiler tell me.
- diN0bot 17y agoyou can use factories for creation, which abstracts the conditionals into nice bundles. you can in a sense do factories regardless of having classes, in that you can always factor code into happy utility methods. the insight is thinking about how much code has to change per update. there are numerous possible situations and conclusions.