Eric Mahurin
1/21/2008 3:39:00 PM
[Note: parts of this message were removed to make it a legal post.]
On Jan 21, 2008 8:34 AM, RHS <RHSeeger@gmail.com> wrote:
> Out of curiosity... operator overloading and it's ilk are (by many)
> considered to be bad things because it can make it hard to figure out
> what's happening in the code, especially for dynamic languages where
> they can change on the fly. The reason for this thought is, I believe,
> because it can be difficult to understand what code is doing if the
> definitions of "standard" operations are or where they come from.
>
> Along those lines, is there a current way to ask Ruby where the
> definition comes from for a given operator or, more generally, method?
> Ie, Ruby needs to do a lookup to find out what definition to use. Is
> there a way to ask it to do that lookup and report the results?
If you are talking about C++ or Python, I would somewhat agree. In those
languages, the operator definition can be defined several places depending
on the types of the operands. In C++, they can be defined in the class for
the left-hand operand, as a regular function, and maybe other places. In
python, you can define operators in either left-hand operand class or the
right-hand operand class (using "reverse" operator methods).
Ruby on the other hand treats operators simply as a different syntax for
method calls. The definition of an operation will always be found in the
class of the first operand. The first operand becomes "self" and the others
are arguments to the method. The method name for operator is usually the
operator itself (unary operators get an "@" to distinguish between binary
operators).
Ruby operator overloading is not evil and not any different than normal
methods (other than some syntax). This feature is great for DSL's and can
give a more natural syntax to the usage of some classes. I wouldn't want to
deal with complex numbers, vectors, matrices, strings, arrays, etc. without
operator overloading.
Also, without operator overloading, Ruby would not have been as consistent
(everything is an object and all functionality comes from methods on
objects) without removing operators altogether. Compare this to Java where
only the primitive (non-object) types can use operators.
Don't let the "by many" (i.e. Java folks) dictate what are dangerous
language features to use. Especially when that judgment was based on a
language you are not using (C++).
p.s. In C++/python, if you limit yourself to only defining operators in the
class of the first operand (like Ruby), operator overloading becomes more
understandable in those languages (just like other methods). It's all the
extra options that make thing confusing.