This post originated from an RSS feed registered with Ruby Buzz
by Jay Fields.
Original Post: Eagerly Initialized Attribute
Feed Title: Jay Fields Thoughts
Feed URL: http://blog.jayfields.com/rss.xml
Feed Description: Thoughts on Software Development
Initialize an attribute at construction time instead of on the first access.
classEmployee defemails @emails||=[] end end
==>
classEmployee definitialize @emails=[] end end
Motivation The motivation for converting attributes to be eagerly initialized is for code readability purposes. Lazily initialized attributes change their value upon access. Lazily initialized attributes can be problematic to debug because their values change upon access. Eagerly Initialized Attributes initialize their attributes in the constructor of the class. This leads to encapsulating all initialization logic in the constructor and consistent results when querying the value of the instance variable.
Discussion I prefer Lazily Initialized Attributes, but Martin prefers Eagerly Initialized Attributes. I opened up the discussion to the reviewers of Refactoring, Ruby Edition and my current ThoughtWorks team, but in the end it was split 50/50 on preference. Based on that fact, I told Martin I didn't think it was a good candidate for Refactoring, Ruby Edition. Not surprisingly, he had a better solution: Provide examples of both refactoring to Eagerly Initialized Attribute and refactoring to Lazily Initialized Attribute.
Martin and I agree that this isn't something worth being religious about. Additionally, we both think it's valuable for a team to standardize on Lazily or Eagerly Initialized Attributes.
Mechanics
Move the initialization logic to the constructor.
Test
Example The code below is an Employee class with both the email and voice_mail attributes lazily initialized.
classEmployee defemails @emails||=[] end
defvoice_mails @voice_mails||=[] end end
Moving to an Eagerly Initialized Attribute generally means moving the initialization logic from the getter methods into the constructor.