The problem with dynamically typed languages

by Brian on 1/7/2008

Here’s a little situation that has happened to me a couple of times in Ruby:

irb(main):004:0> “3″ == 3
=> false

It seems that when comparing a string to a integer does not generate a type mismatch error. But other scripting languages seems to have similar consequences, for example the following Python code:

>>> “3″ == 3
False

Now, take this following snippet from Java:

public class Test {
public static void main(String args[]) {
if(“3″ == 3) {
System.out.println(“True”);
}
}
}

It produces this compile time error:

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Incompatible operand types String and int

at Test.main(Test.java:4)

This creates problems for me when I try to compare data from a database to data taken from, for example, a RESTful API. I run into situations where I unknowingly compare an integer to a string, but without any type checking the code still runs, and the comparison always returns false. It usually takes me extra time to try to debug and troubleshoot what’s happening, but at least now it’s starting to become intuition to consider that the problem might be type. It seems to happening even more often with Rails and ActiveRecord, which return database results of integer fields as integers.

Does anyone have any suggestions or solutions as to how I can prevent this problem in the future? What do you think?

Interesting enough the following Perl fragment:

if (“3″ == 3) {
print “true”;
}

returns true.

Related posts:

  1. Dynamically Typed versus Statically Typed
  2. The Java Guy
  3. How Apple Missed the iPhone 4 Antenna Problem
  4. NoMachine Mac OS X 10.6.3 bug
  5. Filter Sensitive Data From Your Logs

Previous post:

Next post: