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

But it is complicated when that (I'm assuming you mean Pattern 2) switch-case expression is in a large number of locations. Every time you add or remove (in that example) species from your enumeration, you have to address that switch-case in every location (or verify that the default is fine).

By addressing it via (well, I'd use an interface or similar) inheritance the conditional logic isn't removed, but it is isolated to a few decision points. All you need to know is that you have a Foo, and my implementation whether it's a Bar or a Baz will provide the needed functions.



Semi-serious: switch cases are only complicated when you're using compilers that can't check totality for you.


I'll mostly agree with that. If you have a compiler that can check totality (I've been playing with Idris lately at home, that feature is fantastic), then the work of adjusting your switch-cases becomes much easier. But there's still a lot of work relative to, for instance, creating a type class (or in Idris terms an interface) and implementing the functions of that type class/interface for your specific data type.

Similarly, in OO-languages with interfaces, you can apply this same approach. It doesn't eliminate the conditional, it still exists in the code. But it moves where you have to think about it and reduces the redundancy across your code base.

With these things you don't even have to modify every function when you add a new value to your equivalent to an enum, you just add the implementations for that new type/class.

Though it does shift the difficulty when you want to add a new function/method to the interface. Now you will have to go to each implementation and add this new capability. But the nice thing, here, is that most languages with static typing (whether fancy dependently typed languages like Idris, or relatively simpler ones like Java) will make it immediately clear which implementations are incomplete.




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

Search: