3 ms·
def sanity @sanity end def sanity=(val) @sanity = val end how are those six lines not boilerplate?
by xmodem 13y ago
def sanity
@sanity
end
def sanity=(val)
@sanity = val
end
how are those six lines not boilerplate?
- swang 13y agoattr_accessor :sanity
- Schwolop 13y agoattr_accessor :sanity Would be a neater way to write this.
- kourge 13y agoattr_accessor :sanity
- pmahoney 13y agoI suppose the author was trying to be explicit for the sake of a reader unfamiliar with Ruby. The typical way to avoid that boilerplate is by using 'attr_accessor :sanity', which defines those getter and setter methods (and it is possible to implement attr_accessor or similar directly in Ruby, should you need more boilerplate-reducing helpers).
- Skoofoo 13y agoThis is exactly it. I would commonly use the shorthand for something like this, but I felt that it would only deter from the point I was illustrating, which is that a couple methods can seamlessly act like a variable.
- ryanto 13y agoThey are, which is why Ruby's Module (class comes from module) has attr_accessor method. http://ruby-doc.org/core-1.9.3/Module.html#method-i-attr_accessor http://ruby-doc.org/core-1.9.3/Module.html#method-i-attr_acc... The above can be written as attr_accessor :sanity
- dpritchett 13y agoI believe it'd be idiomatic to use attr_accessor :sanity def initialize @sanity = 0 end On that note I like Go's default values for primitive types. An int sanity would be zero by default. Edit: seeing five simultaneous posts saying the same thing makes me feel trolled a bit :)
- damncabbage 13y agoThey are. (And generated behind the scenes by "attr_accessor :sanity", if you'd prefer the short version.) The benefit everything-is-a-message is that you can swap out the implementation of sanity (or sanity=) if needed, eg. Before: attr_accessor :radius, :diameter After: # Refactored radius to be the new source of truth. def diameter radius * 2 end def diameter=(val) self.radius = val / 2 end In PHP (for example), MyClass->diameter and MyClass->diameter() are completely different things. Any existing code (including code you don't control) needs updating to change references from the former to the latter when moving logic into something that was previously static. This article is flawed by holding up those six lines in themselves as something great, but I think the point the author is trying to get across is valid.
- deleted 13y ago[deleted]