Hacker News new | ask | show | jobs
by pansa2 1911 days ago
One issue I have with (pure) OOP is the way that methods are associated with a single type (and its subtypes). What about operations that don’t naturally belong to any one type?

For example, binary operator overloading. With unrelated classes `C` and `D`, should the implementation of `+` to handle `C.new() + D.new()` be added to `C` or `D`? Conversely, if both `C` and `D` define an implementation of `+`, which one should be preferred?

2 comments

I think binary operator overloading is a bit of a stretch here and it usually has clear rules in whatever language you choose.

But the more general question of where to put `combine_with()` in `A.combine_with(B)` is on neither (and not necessarily on another object either).

Unfortunately, this is prevalent in OOP programming but it is simply bad architecture. Of course, with it being so common, it's natural to blame OOP programming, because—in a way—it lets people get away with it easily.

As others have pointed out, the most pragmatic approach is the most reasonable one: use functional paradigms where they make more sense, OO-ones where they do. When things stop making sense (as in your example), don't do it!

To best understand what things make sense, start doing TDD and you'll quickly learn to de-couple things that don't need to be coupled (even if you don't end up doing TDD all the time).

In C++, quoting cppreference.com: "Binary operators are typically implemented as non-members to maintain symmetry (for example, when adding a complex number and an integer, if operator+ is a member function of the complex type, then only complex+integer would compile, and not integer+complex)". This makes perfect sense.

In other languages, I'd say: perhaps implement the operator in the return type of the operation?