Skip to content

Discussion around the banning of alias #377

@marxarelli

Description

@marxarelli

I was surprised to see the suggestion to avoid alias for no other reason than alias_method "will do," and I'm curious to hear what others think. In my experience, there are situations where each can be seen as clearer over the other.

IMO, using alias_method is clearer and less ambiguous than alias—and sometimes the only possibility—when mutating class objects or singletons at runtime. There's a lot of discussion of this out there and, in fact, most proponents of avoiding alias altogether point to these metaprogramming use cases.

However, we're not always metaprogramming. Sometimes we're just linearly implementing methods and want to provide an alias method for whatever reason—perhaps the method is very generic and could conceivably be used in two semantically different ways (inject and reduce come to mind) or maybe there are two forms but one seems more canonical and would benefit from a simpler name.

class List
  def fold_left(&accumulator)
    # yield left to right (head to tail)
  end

  def fold_right(&accumulator)
    # yield right to left (tail to head)
  end

  alias fold fold_left
end

Using alias here seems more appropriate because it's just more like def: 1) it's a keyword; 2) it's lexically scoped; 3) it's declaring a new identifier (not taking object arguments); and 4) it's short and sweet. Putting alias_method here instead would: 1) violate the rule of calling macros before instance method definition (it is indeed a macro in this context); and 2) look awkward due to the inconsistency between its symbol/string arguments and def's identifiers.

Anyway, that's just my 2 cents and I'm curious about other perspectives on it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions