3 ms·
That's an interesting point. I've been wondering for a long time why a lot of people who are exposed to pattern matching in Scala never start using it themselv
by dkarl 7y ago
That's an interesting point. I've been wondering for a long time why a lot of people who are exposed to pattern matching in Scala never start using it themselves, even if they understand it well enough to read pattern matching code without difficulty. It often offers a simple, transparent way to express logic that looks very tricky using if/else, but despite seeing examples they keep reaching for if/else even in awkward cases. And I've observed that they end up adding methods to classes solely to be used in a single piece of if/else business logic, which often (in my opinion) are the concern of the business logic that uses them, not the concern of the class.
And I find that we disagree. When I frame a question as, "How does this algorithm handle this value?" they frame it as, "How does this class behave in this algorithm?" Is the difference in how the types are treated in the algorithm best expressed as the concern of the class (via polymorphism) or as the concern of the algorithm (via pattern-matching)?
I write a lot of OO code with polymorphic methods and am not opposed to modeling things that way, but I think it's often not the best way. I feel like business logic that could be expressed coherently in a single place gets scattered across many classes, and to understand the algorithm you have to gather the logic from a bunch of different places and reconstruct it. Not only that, classes accumulate little fragments of logic that belong to disparate concerns that are supposed to be handled elsewhere. If you have polymorphism and not pattern matching, this is inevitable. If you have both, it can be avoided.