Is there a convention for memoization in a method call?

前端 未结 6 1514
清酒与你
清酒与你 2021-02-19 04:14

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
         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-19 04:53

    I don't like the bang either. I use

    def some_method 
      @some_method_memo ||= some_method_eval 
    end 
    
    private 
    
    def some_method_eval
      # lot's of code 
    end 
    

    Here eval is shorthand for evaluation. I like the way this reads and also that it makes the public interface concise.

    I despise conventions that rely on underscores as distinguishing marks: they are both error prone and require that I remember YAMC (yet another meaningless convention). The Ada language, designed for safety-critical applications, does not allow leading, trailing, or multiple underscores. Nice idea.

提交回复
热议问题