Skip to content

Bring On The Immutability

umermansoor edited this page Nov 26, 2012 · 19 revisions

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

A class which is unmodifiable or immutable, is thread-safe, easy to manage, high performant, and a great building block for other objects.

Consider the following example of an Immutable class:

/** 
 * 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);
    }
 }