http://www.perlmonks.org?node_id=485961


in reply to Re: Things I Don't Use in Perl
in thread Things I Don't Use in Perl

I find overloaded operators very useful in the limited context of mathematical objects such as vectors and matrices. They can make these kinds of formulas more legible IMHO: I'd rather have
$z = $x x $y / ($x . $y)
than
$z = $x->cross($y)->divide_by($x->dot($y));
(See the Math::VectorReal module, for example).

Replies are listed 'Best First'.
Re^3: Things I Don't Use in Perl
by chester (Hermit) on Aug 23, 2005 at 18:20 UTC
    It definitely makes the equation easier to read, but I'm not sure if it makes the code easier to read. You can't easily tell that "." may be doing tons of matrix operations (or who knows what else), not concatenating some strings. It looks like standard Perl, but it's not really Perl, it's mathematics. But on the other hand, people may already have a strong preconception of what "." means with regards to matrix manipulation. And it's easier/faster to type. I can see your point.
      It's all in the context. If that line of code is part of a vector algebra program, in a subroutine called "rotate_vector", and the names of the variables suggest that they might be vectors, it should be pretty obvious what the dot means. ;-) But yep, in some other context it might be confusing.
Re^3: Things I Don't Use in Perl
by Anonymous Monk on Aug 25, 2005 at 17:31 UTC
    The only reason you find those overloaded operators useful in the context of mathematics is that, in general, those symbols have already been overloaded as part of the standard mathematical notational. You're just conforming with a pre-existing convention; and convention is the only reason that such overloading appears natural to you.

    For coding, I prefer to conform to the larger convention: I don't redefine symbols, because I don't need to redefine symbols, and the small gain I get from standardization with a localized mathematical convention is washed out by the big loss in standardization for general coding conventions.

    I guess I don't like code that reads:

    $x = $y + $z; # delete all files if running as user wilbur

    which is exactly what operator overloading allows. Specifically, it removes any guarantees that I once had about what is being done to what, when. Instead, every single line is suspect, and must be read in a much wider context to verify correctness, which I see as a huge loss for maintainability.

    Sooner or later, someone will make a deliberate or accidental piece of malicious code, and the easier it is to track it down, the better.

      I guess I don't like code that reads:
      $x = $y + $z; # delete all files if running as user wilbur
      Bad names are bad names whether they are overloaded or not. If you can't trust your programmer to choose sensible times to overload an operator, why would you trust him in selecting subroutine names at all?
      $x = fluffy_bunnies_are_cute($y,$z); # delete all files