Why does rubocop or the ruby style guide prefer not to use get_ or set_?

Harish Kayarohanam picture Harish Kayarohanam · Sep 29, 2014 · Viewed 9.3k times · Source

I was running rubocop on my project and fixing the complaints it raised.

One particular complaint bothered me

Do not prefix reader method names with get_

I could not understand much from this complaint so I looked at source code in github.

I found this snippet

    def bad_reader_name?(method_name, args)
      method_name.start_with?('get_') && args.to_a.empty?
    end

    def bad_writer_name?(method_name, args)
      method_name.start_with?('set_') && args.to_a.one?
    end

So the advice or convention is as follows:

1) Actually they advice us not to use get_ when the method does not have arguments . otherwise they allow get_

2) And they advice us not to use set_ when the method has only one argument .otherwise they allow set_

What is the reason behind this convention or rule or advice?

Answer

Stefan Dorunga picture Stefan Dorunga · Sep 29, 2014

I think the point here is ruby devs prefer to always think of methods as getters since they returns something and use the equals "syntactic sugar" (like in def self.dog=(params) which lets you do Class.dog = something). In essence the point I've always seen made is that the get and set are redundant and verbose.

In opposition to this you have get and set with multiple args which are like finder methods (particularly get; think of ActiveRecord's where).

Keep in mind that 'style guide' = pure opinion. Consistency is the higher goal of style guides in general so unless something is arguably wrong or difficult to read, your goal should be more on having everything the same than of a certain type. Which is why rubocop let's you turn this off.