Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re: Why get() and set() accessor methods are evil

by inman (Curate)
on Nov 25, 2003 at 17:30 UTC ( #309970=note: print w/replies, xml ) Need Help??

in reply to Why get() and set() accessor methods are evil

The key to all things OO is encapsulation. Basically you publish an interface which people then use. If you start changing the behaviour of the interface then you are going to cause problems. The thing to remember is that accessor methods are as much a part of the encapsulation as constructors or other more conventional methods and should be treated with the same respect. The problem that has been highlighted is that the lazy implementation of get/set functions as a thin layer over the top of the internal representation is brittle and may cause a maintenance headache.

In your example you have a method (sub) called get_array. You have published an interface that says 'Whenever you invoke this method you will get an array to work with'. This is in effect a contract between you, the designer of the class and whoever uses your class. When the internal representation of the data changes to a hash, the get_array method will end up doing more work since it now needs to construct an array to pass back to the caller. Thus maintaining the contract and not causing problems.


Replies are listed 'Best First'.
Re: Re: Why get() and set() accessor methods are evil
by synistar (Pilgrim) on Nov 25, 2003 at 19:18 UTC
    This is exactly the problem I was trying to bring up ( much better worded by you). If you don't take care with how you use accessors making changes later can force you to change your interface. In general I think a good rule of thumb is to try an avoid accessor methods. However, I can see a few cases where you do need to use public accessors (the CGI module's param() method and some templating modules for example).

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://309970]
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2023-12-06 03:41 GMT
Find Nodes?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?

    Results (29 votes). Check out past polls.