4 ms·
> operator overloading, while it can make for cute-to-read code, isn't really a good idea for code readability and maintenance so should we write `add_int_int(
by moelf 1y ago
> operator overloading, while it can make for cute-to-read code, isn't really a good idea for code readability and maintenance
so should we write `add_int_int(1,1)` and `add_int_double(1, 1.0)` and `add_double_double(1.0, 1.0)`?...
- HarHarVeryFunny 1y agoThe expectation is that arithmetic operators are performing the corresponding arithmetic operations, so overloading for different arithmetic types (int, float, complex) doesn't produce any surprises or need to lookup operator definitions. Applying arithmetic operators to non-arithmetic types starts to become a problem, even if some cases (set union/difference, string catenation) are natural... The same goes for other operators... overloading '[]' indexing for maps as well as arrays seems natural, but would be highly confusing if you overloaded it for something unrelated to an index-like concept.
- JadeNB 1y agoI think a problem here is that everyone has a different idea of when you hit the boundary between obvious/non-surprising and confusing, so you can't just say that overloading is OK as long as it is unsurprising.
- HarHarVeryFunny 1y agoJust because people have differing opinions (some well founded, some not!) doesn't mean that defining best practices doesn't make sense. Code readability and lack of surprise objectively are good things, and certainly important for large enterprise projects. I think there are two alternate guidelines for use of operator overloading that would make sense. 1) Just don't overload operators at all for your own types! Leave that to the standard libraries and types that they define. OR 2) Overload, but keep to the semantics of the operators as used by the language's built-in types (e.g. use arithmetic operators for arithmetic operations, comparison operators for ordering operations, etc). If your project was using a style guideline like this, then violations would be caught by code review (maybe automated by AI in the future?).