Comparing Constants Safely

When comparing two objects, the equals method is used to return true if they are identical. Typically, this leads to the following code :

if (name.equals("Jim")) {

The problem here is that whether intended or not, it is quite possible that the name value is null, in which case a null pointer exception would be thrown. A better practice is to execute the equals method of the string constant “Jim” instead :

if ("Jim".equals(name)) {

Since the constant is never null, a null exception will not be thrown, and if the other value is null, the equals comparison will fail.

If you are using Java 7 or above, the new Objects class has an equals static method to compare two objects while taking null values into account.

if (Objects.equals(name,"Jim")) {

Alternatively if you are using a java version prior to Java 7, but using the guava library you can use the Objects class which has a static equal() method that takes two objects and handles null cases for you. It should also be noted that there are probably a number of other implementations in various libraries (i.e. Apache Commons)

Immutability Through Interfaces

It is often desirable to have immutable objects, objects that cannot be modified once constructed. Typically, an immutable object has fields that are declared as final and are set in the object constructor. There are getters for the fields, but no setters since the values cannot be saved. Once created, the object state doesn’t change and the objects can be shared across different threads since the state is fixed. There are plenty of caveats to that statement, for example if you have a list, while the list field reference may be final, the list itself may be able to change and have values added and removed which would spoil the immutability.

Achieving this state can often be difficult because we rely on a number of tools and frameworks that may not support immutability such as any framework that builds an object by creating it and then setting values on it.

However, one way around this would be to take a mutable object and make it immutable through interfaces. We do this by creating an interface that represents all the getters for an object, but none of the setters. Read More »