The Artima Developer Community
Sponsored Link

Scala Buzz
Refactor: Lazy Initialisation to Eager

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Ricky Clarkson

Posts: 63
Nickname: rclarkson
Registered: Jul, 2006

Ricky Clarkson is a salsa-dancing, DJing programmer in Manchester, England.
Refactor: Lazy Initialisation to Eager Posted: May 15, 2010 1:25 PM
Reply to this message Reply

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.
Latest Scala Buzz Posts
Latest Scala Buzz Posts by Ricky Clarkson
Latest Posts From Ricky's technical blog

Advertisement
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:

Read: Refactor: Lazy Initialisation to Eager

Topic: Implicit tricks -- the Type Class pattern Previous Topic   Next Topic Topic: Scala Stream Fusion and Specialization, Part 2

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use