Skip to content

Bring On The Immutability

umermansoor edited this page Nov 29, 2012 · 19 revisions

Rule: Constants - or unmodifiable variables - are excellent. Use them more often.

A class which is unmodifiable or immutable, is thread-safe, easy to manage, high performant, and 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;

     /**
     * PRIVATE CONSTRUCTOR
     */
     private final SmgServer(String host, String ip, int port) { //Assign Variables }

    public static valueOf(String host, String ip, int port)
    {
        return new SmgServer(String host, String ip, int port);
    }
 }