Immutable Objects

This week’s post offers a review of theconcept of immutable classes, and suggestions for best practices inimplementation.  An immutable class is “aclass whose instances cannot be modified” (Bloch, 2018, p. 80) . There are many well-known immutable classes in the Java platformlibraries such as String and primitive classes like Integer and Double (Temre, 2015). To illustrateconsider a simple example of a Car class.

A simple Car class might have the attributesownerName, modelYear, maker, model, licensePlateNumber, and color.  This simple class might do well to collectCar objects for public service reasons such as police patrol or license feemonitoring.  To create this class asimmutable, these fields must be declared private and final, create no settermethods, make sure not to use any mutable objects in the constructor, and don’tallow getter methods to be overridden (Tinca, 2018).  Once crafted as an immutable class, each Carobject is set and cannot be changed.

Advantages

There are many advantages of immutableobjects derived from immutable classes including (2018, pp. 81-83):

  • Immutableobjects are simple and stable, remaining in the original state in which theywere created.
  • Immutableobjects are thread safe, i.e. they cannot be corrupted by multiple threads accessingthem concurrently.
  • Immutableobjects can be shared freely.
  • Immutableobjects make great building blocks for other objects.

Sheikh has also demonstrated that the use ofimmutable classes generally leads to easier class and project testing overall (2018). 

Disadvantages

Bloch suggests that there is limited downsideto using immutable classes, that being primarily that in some cases a largenumber of instances may be required, expanding program processing demands andhampering performance (2018, pp. 84-86). 

Sheikh emphasizes that “one of the main disadvantagesof Immutable objects is that you end up with a lot of boilerplate code” (Sheikh, 2018).  Sheikh continues to explain that theprogramming requirements for properly coding immutability could besubstantial.  Software engineer LuisEspinal agrees with Sheikh, suggesting that “immutability in most OO languagesforces you to add artificial artifacts and practices in your model and process.For each complex immutable class you must have an equally complex (at leastinternally) builder” (Espinal, 2011).

The downside of immutable classes can be seenwith the simple Car class example above. The problems with immutable objects surface when the object once createdno longer reflects the reality being studied. For example, if a Car object is sold ownerName will no longer bevalid.  To keep the car object in theclass, a new object will have to be created. When this problem grows large, it can be a burden to the program to haveto constantly be creating entire new objects instead of modifying the onesalready on hand.

BestPractices

Overall, Bloch recommends that “classesshould be immutable unless there’s a good reason to make them mutable,” as theyoffer “many advantages and their only disadvantage is the potential forperformance problems” (2018, p. 86).  However, Bloch’s discussion on the issuefalls short of definitive guidance for when an immutable class is the bestalternative.

Espinal suggests that the developer shouldconsider carefully the nature of objects being created before committing to animmutable class structure.  He goes on toformalize his recommendation that “small, possibly unitary things can be madeimmutable,” but more complex things should be made immutable only when it“makes sense” (2011). 

Based on the many advantages of immutableclasses, along with the main disadvantages of program complexity and potentialprocessing burden, this post recommends the use of immutable classes whereverfeasible, with special emphasis on the three questions posited by Loritsch (2011).

  1. Is there abusiness reason why an object can change its state?  If so, using an immutable class may presenttwo problems.  First, the class objectdoes not match the business logic which can lead to further developmentissues.  And, secondly, the frequentconstruction of replacement objects may lead to processing burden.
  • Are some of the attributes computed?  If so, this raises complexities as immutableobjects interact with computed objects from other classes, which must also beimmutable.  This chain reaction ofimmutability needs to be handled carefully.
  • How many values make up the object underconsideration?  As Loritsch states, “atsome point the complexity of creating and re-creating immutable objects becomesnon-trivial and, at that point, having more instances of the object can becomea problem” (2011).

References                                          

Bloch, J. (2018). Effective Java Third Edition. Boston: Addison-Wesley.

Espinal, L. (2011, April 14). At what point to immutable classes become a burden? Retrieved from StackExchange.com

Loritsch, B. (2011, April 14). At what point to immutable classes become a burden? Retrieved from StackExchange.com

Sheikh, W. (2018, June 9). Understanding immutability. Retrieved from Medium.Com

Temre, K. (2015, May 2). Complete list of immutable jdk classes? Retrieved from StackOverFlow.Com

Tinca, I. (2018, March 5). About immutability in OOP. Retrieved from DZone JavaZone

Leave a Comment

Your email address will not be published. Required fields are marked *