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.

Leave a comment