Why I hate weak typing

I just wasted at least two hours hunting down a bug that turned out to be in this PHP code fragment:

      if ($reader->hasValue) {
        echo ": " + $reader->value;

Do you see the bug?

The problem is that I’m using the arithmetic addition operator + instead of the string concatenation operator .. If PHP were more strongly typed it would have complained about my attempt to concatenate two strings using a purely numeric operator. Instead it silently converted each string to a number (I’m not sure exactly how), added those numbers, and echoed the resulting integer.

It didn’t help that I wasn’t very experienced with the API I was using so I didn’t initially realize that the almost plausible output I was getting was a result of my bug and not some weirdness in the library.

4 Responses to “Why I hate weak typing”

  1. Bruce Eckel Says:

    Hmm. It’s not clear to me exactly what you are saying here. I think you are having problems with PHP’s automatic type conversion, rather than an issue where the wrong type is slipping through a hole in the language (which is what weak typing is; and yes, I know I’m at least partially responsible for the misuse of that term).

    If the problem arises from the fact that PHP doesn’t do a preliminary type-checking pass and tell you about the problem, or at least tell you that it’s doing a conversion that you may not like, then that would be a lack of static type checking, not weak typing.

    Sorry to be a language lawyer but in this case it really does make a big difference in clarity of communication.

  2. Elliotte Rusty Harold Says:

    I’m using an arithmetic operator + to add a non-numeric type to a numeric type, and PHP <em>helpfully</sarcasm> treats the string literal as a number to make that work, even though there’s no sensible interpretation of the string ": " as a number. This is pretty weak. A string literal should not be allowed where a number is expected. This should be a compile time error. If it had been, I would have found it the first time the script errored out.

  3. John Cowan Says:

    A long time ago, dedicated Fortran II types used to bitch because some compilers would automatically coerce an integer to a float (“mixed-mode arithmetic”) without making you write an explicit type conversion. They no longer work here.

  4. Steven Says:

    Totally agree!

    I hate weak typing, too!

Leave a Reply