3 ms·
Regarding Ruby's attr_accessor automatically 'generating' getters and setters: If all you're doing is returning the internal value, or setting it blindly to th
by georgieporgie 16y ago
Regarding Ruby's attr_accessor automatically 'generating' getters and setters:
If all you're doing is returning the internal value, or setting it blindly to the value provided, why bother? Why not just directly access the member variable if you're not doing any parameter validation or business logic?
Does Ruby provide some syntactically elegant mechanism for adding logic to the getters and setters? Because as it stands, it looks like Ruby has an elegant solution for a problem that didn't actually exist.
- regularfry 16y agoIn Ruby, you can't[0] access an instance variable without an accessor; they're private by default, with all that implies. Also, when you use attr_accessor, all it does is literally[1] create a getter and a setter method. Adding logic to them later is a simple matter of replacing the attr_accessor shortcut with a method with the right name. None of the client code has to change, and that's the important part. [0] Not quite; see Object#instance_variable_get. But that's cheating, ugly, and generally frowned upon. [1] Not quite, but the difference is an implementation detail.
- lulin 16y agoAs Ruby instance variables are private, you need a getter to read them. Doing it this way (making everything private, but giving you simple methods for creating getters and setters) gives you the best of both worlds: Encapsulation and simple and concise code. attr_accessor simply creates the boilerplate code you would write yourself or use an IDE for in other languages. If you want to change a getter, just write a new method with the name of the variable and do whatever you want. This makes it easy to change your class logic later, but won't fill your classes with generic getter/setter code.