This post originated from an RSS feed registered with Scala Buzz
by Ricky Clarkson.
Original Post: Refactor: Lazy Initialisation to Eager
Feed Title: Ricky's technical blog
Feed URL: http://rickyclarkson.blogspot.com/feeds/posts/default
Feed Description: A blog about programming languages, and Java.
A field is being initialised when used, rather than when the object is created.
Extract the initialisation into a separate method that returns the value to store in the field, move the assignment to the field declaration, and inline any private use of the getter.
becomes
Motivation
The lazy initialisation is no longer necessary, and harms readability. Additionally, incorrect lazy initialisation can cause problems for concurrent programs.
Mechanics
Where the field is assigned, redeclare a variable shadowing the original field. Rename that variable including its uses, and at the end of the block assign the new variable to the field:
Extract a method for the operations on the new variable. This should be static, at least during the refactor, to prevent accidental operations on other fields. Other fields' values should be passed in explicitly as parameters. This helps to prevent initialisation-order problems (where y gets initialised before x, but while initialising y, we read x and get a big fat null).
Get rid of the == null check, and make the field final: