-
Notifications
You must be signed in to change notification settings - Fork 2
Bring On The Immutability
First, read Rule #1. Constants - or final
variables - are amazing. Use them whenever you can, in fact, strive for constants.
A class which consists only of constants can only ever be in one state: the one it was created in. Recalling code example in Rule #1, a Person class can only have one state for the name
and birthDate
variable, which is the one set during construction. A class consisting only of constants is effectively unmodifiable and called: Immutable. Immutable classes hold a special place in my heart and I love them deeply (j/k). They are called immutable because once created, their state cannot ever be changed.
One reason only: it's because these classes are Thread Safe. Java guarantees that if a class is immutable, it can be freely shared amongst threads without any synchronization, whatsoever. Hence such classes are a great building block for other objects.
Given below is an example of an Immutable class. Such as class can be shared freely amongst threads without any external synchronization:
/**
* To represent SMG server as TCP end point
* @author umansoor
*/
public class SmgServer
{
private final String hostname;
private final String ipaddress;
private final int port;
// -- Note: Look ma, a private constructor.
private final SmgServer(String host, String ip, int port) { //Assign Variables }
public static SmgServer valueOf(String host, String ip, int port) {
return new SmgServer(String host, String ip, int port);
}
}
In the example above, all the variables are constants as they are marked by final
and their values are set in the constructor. Look at the access level of constructor and you'll notice that I have made it private
. It is a common convention for immutable classes to define a static
function called valueOf(...)
which takes in the arguments, creates the immutable object by calling its private
constructor and returns its value, which is the Object if all went well. This is just a convention which the Java built-in classes (e.g. b = Boolean.valueOf(true)
) and the community follows religiously.