Clear questions and runnable code get the best and fastest answer |
|
PerlMonks |
•Re: OO Getters/Settersby merlyn (Sage) |
on Dec 31, 2003 at 16:46 UTC ( [id://317930]=note: print w/replies, xml ) | Need Help?? |
An object's interface to the "outside" is its methods. The methods should be thought out well, because refactoring and upward compatibility demand that those methods retain the same or better functionality over time when installing "plug-replacable" parts.
There are times when a method's natural implementation is to take a parameter and alter an instance variable directly, or to fetch an instance variable and return it with minimal fuss. For these, an automatically-constructed getter or setter is quite expedient. But the blanket "give every instance variable a getter/setter" strategy is nearly always a sign that the coder is not yet "thinking objects", as you point out. Methods should be named by the "what" it does, and not "how" it gets done. For example, consider a two-space point type, with a natural X and Y value for the addressing. I might initially create the traditional getter/setter for these two independent values. But let's say later that I discover that more often than not, I need these values as rho and theta in polar space, so I decide to change the internal representation to polar space. With separate X and Y setters, I have to perform more needless calculations as I update each one, where if I had just given an interface initially that only set both at once, my calculation burden would have been reduced. Yes, there are holes in that example... that's just a quick thought. The point is that providing attribute-based setters instead of functional interfaces means you are bound to support an interface that may be expensive later when you change the design. I hope that's clear. -- Randal L. Schwartz, Perl hacker
In Section
Seekers of Perl Wisdom
|
|