Search
⌘K
    to navigateEnterto select Escto close

    Use underscore prefix for memoization

    Let's look at code.

    1class UsageReportCarrier
    2
    3  attr_reader :health_agency
    4
    5  def initialize health_agency
    6    @health_agency = health_agency
    7  end
    8
    9  def managers
    10    @managers ||= health_agency.health_agency_users
    11  end
    12
    13end

    In the above code method managers is using memoization. However memoization like this makes code less confident since @ has a special meaning in ruby. When we see @managers we start thinking where else it is being used. Is there an attr_reader for it or not. Is someone directly messing with this instance variable. Overall it gives impression that there might be more to it than just memoization.

    In order to make the intent of memoization absolutely clear we prefer to use

    1def managers
    2  @_managers ||= health_agency.health_agency_users
    3end

    This makes it absolutely clear that here the intent of using @ is just to do memoization and nothing else.

    Previous
    Next