3 ms·
"Type-sensitive" code is encouraged when using the functional style, where you treat objects as dumb "bags of data" that have no inherent functionality of their
by thurn 7y ago
"Type-sensitive" code is encouraged when using the functional style, where you treat objects as dumb "bags of data" that have no inherent functionality of their own. It's still discouraged when following an object-oriented "smart objects" pattern.
- bernawil 7y agoHow is that particularly functional? In Haskell the same example would be approached at type-level using type classes, something extremely similar to using Interfaces. I guess in a dynamic functional language you'd probably avoid doing this type of contact-oriented stuff, but you'd rather pass a callback at the last point rather than check type of what you got passed.
- emodendroket 7y agoI worked in Scala for a while and it was pretty common to use these kind of pattern-match statements for a kind of dispatch mechanism. Not even necessarily with types, it might be something like "do one thing when field a is null and field b is not, another thing when it's the other way around, another thing when they're both null, and still another when neither is." The nice thing about it is the compiler can assert that your match is exhaustive.
- bernawil 7y ago> do one thing when field a is null and field b is not And that would have been a good example! contrary to the one in the docs. Pattern matching for checking fields of things of the same type is a good use. Pattern matching when checking your parameters type? bad. > The nice thing about it is the compiler can assert that your match is exhaustive If you pass a new Shape object for which you forgot to implement a new case in the pattern matcher, you just get the default case, which is wrong, but the compiler can't know that. Now have the function argument ask for something that implements IArea interface and if you don't implement getArea() in your new Shape class, the compiler will know.
- emodendroket 7y agoWell I think it is pretty common to have a combination of these. You're right that if you configure a default matcher the compiler can no longer tell if the match is as exhaustive as you intended, but I think you can often just avoid that altogether.