→ return early

15 December 2009

I often see code like this:

def logger
  unless @logger
    @logger = Logger.new(STDOUT)
    @logger.level = Logger::WARN
  end
  @logger
end

What you really want to do is return the instance variable if it's already set. So why not do that?

def logger
  return @logger if defined? @logger
  @logger = Logger.new(STDOUT)
  @logger.level = Logger::WARN
  @logger
end

Or you could cache bang it.