The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Ruby: Lazily Initialized Attributes

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
Jay Fields

Posts: 765
Nickname: jayfields
Registered: Sep, 2006

Jay Fields is a software developer for ThoughtWorks
Ruby: Lazily Initialized Attributes Posted: Jul 29, 2007 12:47 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Jay Fields.
Original Post: Ruby: Lazily Initialized Attributes
Feed Title: Jay Fields Thoughts
Feed URL: http://blog.jayfields.com/rss.xml
Feed Description: Thoughts on Software Development
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Jay Fields
Latest Posts From Jay Fields Thoughts

Advertisement
Lazily Initialized Attributes

Initialize an attribute on access instead of at construction time.

class Employee                      class Employee
def initialize def emails
@emails = [] => @emails ||= []
end end
end end

Motivation
The motivation for converting attributes to be lazily initialized is for code readability purposes. While the above example is simple, if the Employee class has multiple attributes that need to be initialized the constructor will need to contain all the initialization logic. However, lazily initialized attributes can encapsulate all their initialization logic within the methods themselves.

Mechanics
  • Move the initialization logic to the attribute getter.
  • Test
Example
The code below is an Employee class with the email attribute initialized in the constructor.

class Employee
attr_reader :emails

def initialize
@emails = []
end
end

Moving to a lazily initialized attribute generally means moving the initialization logic to the getter method and initializing on the first access.

class Employee
def emails
@emails ||= []
end
end

Read: Ruby: Lazily Initialized Attributes

Topic: at icanhasruby tonight Previous Topic   Next Topic Topic: Testing Across Browsers without the Browser

Sponsored Links



Google
  Web Artima.com   

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