Search code examples
rubycoding-stylememoization

Is there a convention for memoization in a method call?


I want to avoid reevaluation of a value in method call. Untill now, I was doing this:

def some_method
  @some_method ||= begin
    # lot's of code
  end
end

But it ends up quite ugly. In some code, I saw something like the following:

def some_method
  @some_method ||= some_method!
end

private

def some_method!
  # lot's of code
end

I don't like the bang (!) at the end, so I came up with this:

def some_method
  @some_method ||= _some_method
end

private

def _some_method
  # lot's of code
end
  • Is prepending with an underscore a good convention?
  • Is there some other convention for memoized/non-memoized pairs of methods?
  • Is there some convention to memoize multi-line methods?

Solution

  • I would do it like this:

    def filesize
      @filesize ||= calculate_filesize
    end
    
    private
    
    def calculate_filesize
      # ...
    end
    

    So I'd just name the method differently, as I think it makes more sense.