Don't use Java primitives

3rd July 2009

Java syntax evolved from C’s and as a result has the primitives:

byte short int long float double boolean char

These primitives can be considered to be the building blocks for all other value objects within Java and allow users to hold data as fields and variables. However, I would argue that they are not useful and a good rule of thumb is to not use them at all. Instead Java provides the classes:

Byte Short Integer Long Float Double Boolean Character

These are classes for fully fledged, immutable, value objects which can be used in much the same way as the basic primitives, but offer the following advantages:

1. They can be used in generics. This is possible:

new ArrayList<Integer>();

But this is not:

new ArrayList<int>();

2. They can still be passed into library functions that demand primitives. Auto boxing means that a method signature with int can still be called with an Integer objects transparently. Likewise, a function returning an int can be assigned to an Integer.

3. They offer all the expected methods for use in debugging and collection handling, such as toString, equals and hashcode.

4. They can be null. While there is a lot of discussion as to whether applications should be passing null around, it is still sensible to ask the question what should be returned from a method such as getIdIfPresent if there is no ID. With primitives, you’d be forced to return a value that represented a nonexistent result, such as -1. WIth real objects, you have the option of returning null.

5. Primitives in java are passed by value, whereas objects in java are passed by reference. This may not have a huge impact on how you would handle Integer vs int, however. This is because the objects that represent the primitive types are immutable, and therefore you cannot change the value of any of the parameters passed. Despite this, I would recommend using objects over primitives, simply because it means you don’t have two kinds of behaviour represented in your code.

tags: java, post
blog comments powered by Disqus