3 ms·
As a real world (-ish) example, I wrote some Python code to do some effects on DMX lights. OpenLighting did all the talking to the lights, so the Python code w
by Mister_Snuggles 7y ago
As a real world (-ish) example, I wrote some Python code to do some effects on DMX lights. OpenLighting did all the talking to the lights, so the Python code was really just focused on constructing a list of numbers that would eventually find their way into OpenLighting and onto a DMX cable.
Inside the Python code, each light has a Colour, and I built the Colour class with support for various math operators.
Want to make a Colour that's half as bright as another? Colour = OtherColour * 0.5. Want to blend two Colours? BlendedColour = OneColour + AnotherColour.
Doing this made all of the stuff that the code was doing incredibly obvious and straight forward. The alternative would have involved non-obvious helper functions and object methods or doing math directly on the rgb components encapsulated by each Colour object.
This was, for me, somewhat of a "light bulb" moment for operator overloading.
- maxxxxx 7y agoIf it's done in good taste overloading is fine. But if abused it makes code totally unreadable and unmaintainable.
- fauigerzigerk 7y agoColor me skeptical :) The reason why unnamed operators work so well for math code is that their meaning is already well established. OneColor + AnotherColor does not have any obvious meaning. If colors are RGBA vectors, it could be vector addition. But is that what your blend operation does? What's wrong with: BlendedColor = blend(OneColor, AnotherColor)
- Mister_Snuggles 7y agoI agree, this is where you have to be careful. The meaning makes sense to me which, for a one developer codebase, is OK, but it's not something I'd want to do in a codebase supported by a larger team. I expect that in a more complete product that even the term "blend" would have multiple meanings.