How to cache values in a variables

April 6, 2009

Coming from a .NET background I was always used to using properties in my classes in order to either expose the values of my variables to the consumer of my class or to perform some sort of caching so I don’t have to have the same logic duplicated throughout my class.
An example of that code might look like this:
public class TestClass
{
string _firstName;
public string FirstName
{
get
{
if(string.IsNullOrEmpty(_firstName))
{
_firstName = UserDAL.GetFirstName();
}
return _firstName;
}
}
}

After starting to learn Ruby On Rails I have learned that there is a very simple way to do the same thing with much less code.

def class TestClass
 def first_name
  @firstname ||= User.first.FirstName
 end
end

One thing to watch out for is that the ruby code above checks to see if the value of the variable is not null and it will return the value that is set. This means that if you wanted to return a result based on a constantly changing criteria then this is not the correct way of performing caching because the statement that occurs after the “||=” only gets evaluated once unless the result of that statement returns nil.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: