Quantcast
Channel: User AnoE - Stack Overflow
Viewing all articles
Browse latest Browse all 37

Answer by AnoE for Why does rubocop or the ruby style guide prefer not to use get_ or set_?

$
0
0

Another way to see it: the getter/setter paradigm was, as far as I can tell, largely a specific convention in Java/C++ etc.; at least I knew quite a few Java codebases in the very foggy past where Beans were littered with huge amounts of get_-getters and set_-setters. In that time, the private attribute would likely be called "name" with "set_name()" and "get_name()"; as the attribute itself was called "name", the getter could not be "name()" as well.

Hence the very existence of "get_" and "set_" is due to a (trivial) technical shortcoming of languages that do not allow the "=" in method names.

In Ruby, we have quite a different array of possibilities:

  • First and foremost, we have name() and name=(), which immediately removes the need for the get_ and set_ syntax. So, we do have getters and setters, we just call them differently from Java.

  • Also, the attribute then is not name but @name, hence solving this conflict as well.

  • Actually, you don't have attributes with the plain "obj.name" syntax at all! For example, while Rails/ActiveRecord pretends that person.name is an "attribute", it is in fact simply a pair of auto-generated getter name() and setter name=(). Conceptually, the caller is not supposed to care about what "name" is (attribute or method), it is an implementation detail of the class.

  • It saves 4 or 3 key presses for each call. This might seem like a joke, but writing concise yet easily comprehensible code is a trademark of Ruby, after all. :-)


Viewing all articles
Browse latest Browse all 37

Latest Images

Trending Articles





Latest Images