Brad Fitzpatrick (brad) wrote,
Brad Fitzpatrick

Overloaded operators

A lot of languages have these magical types that internally have a type (number vs. string) but don't really act like it. If the language is designed well, you should never have to know about this little detail.

Of course, it always shines through when you have polymorphic overloaded operators. Perl's good for the most part since it has number vs. string operators (concatenate is ".", not "+", "lt" not "<", etc...)

But Perl still has one fault.... the bitwise operators. Which are bitwise numeric operators when either are numbers, but a bitwise string operator when both are strings. Which is pretty much the most useless operation ever, and the one you get almost all the time, since Perl numbers tend to be string internally when you get them from a user, database, etc.

So whenever you want to do a bitwise operation, your Perl looks like this:

my $bitwise = ($foo + 0) & ($bar + 0);

Just to cast those bitches internally into actual numbers and to be sure you're getting the right operator.

I can live with that in Perl. It's just one operator, and one you don't tend to use that often.

But in JavaScript it's a dozen times worse, since there are no "cmp", "lt", "gt", ".", etc operators for strings, so JavaScript is always guessing what the fuck operator you actually want.

Particularly bad is the "+" operator which either means concatenate or add, both common operations! So you end up sprinkling all your code with stuff like:

var sum = (foo - 0) + (bar - 0);
var sum = (foo * 1) + (bar * 1);

What's worse, it seems that functions in the standard JavaScript library (Math.*, etc) are inconsistent between browsers with regard to shortcuts they take to return early, passing back copies of your original variable without the internal "I'm a string!" flag changed to "I'm a number!".

So it's possible to get back strings variables from Math functions sometimes? (???)

So frustrating, that you can't write a simple numeric algorithm that work in a bunch of browsers without "cleaning" your variables all over the place to make sure they're actually numbers.

I think some of this is fixed in JavaScript 2.0, albeit with a horrid syntax.

Update: had wrong Perl operator as example. brainfart. also s/polymorphic/overloaded/. i should know better.
Tags: hate, javascript, perl, tech
  • Post a new comment


    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.