Sunday, May 9, 2010

Java and Object.

When is an object not an object?

When it's a Java primitive data type.

One of the nice things about Smalltalk is that everything is an Object. Every object in a Smalltalk system understands "printString" or "copy". But in Java, integers and booleans, two of the most commonly used objects (which they aren't...) have to be handled completely differently.

Neither integers nor booleans have any methods whatsoever. You can't do "1.toString()". You can't do "1.compareTo(2)". I find this annoying.

Java tries to remedy this by making Object wrappers for Integer, String, Boolean and so forth. Then they hacked the language to automatically convert between the primitive and the wrapper. The wrappers, however, aren't transparent and are a leaky abstraction.

Take, for example, SQL ResultSets. I find myself doing:

q.setString(1, "hello");
q.setFloat(2, 1.25);
and then:
q.setInteger(3, 45);

But there is no "setInteger" method on a PreparedStatement. It is "setInt", probably because it is passed an "int" rather than an "Integer" as a parameter.

No comments:

Post a Comment