Showing posts with label Java Getters Setters Software Object Oriented Programming OOPS. Show all posts
Showing posts with label Java Getters Setters Software Object Oriented Programming OOPS. Show all posts

Sunday, December 14, 2008

Getters and Setters

Excerpts from Ketan Padegaonkar's blob

"Why do we need getters and setters anyway ? Do they not break encapsulation ? There’s two schools of opinions I’ve come across here. One that likes to follow the javabeans specfications. The other that says hates getters and setters for the reason that objects then tell you who their friends are (Disclosure: I belong to such a group). Objects should expose behavior and not their friends that may help you out."

Interesting!!! Now lets analyse a few points on getters and setters.

Objects like value objects and model elements which are used to store only data will require getters and setters to access the stored data. What about the rest of objects which we see in our daily developer life. Can we live without getters and setters in those objects?

For eg: (In Java)

Parser parser = new Parser("c:\temp\FileToParse.xml");
parser.parse();
parser.getFile();

The 'parser. parse()' method makes sense. What about the 'parser.getFile()' method?

The parser will return the current file which it has parsed. Can we live without this getter? This is an extra information. Do we need to expose this extra information to the user of this parser?

Extra info is always useful. But isn't too much info cumbersome?

Are these extra getters adding oil to the current fire of 'lots of dependencies between packages' which is the case of many huge applications we see today? One day these haphazard dependencies will kill these applications one after the other.

If the getFile() method is exposed by the parser, it will be used by some of the client programs. But if the getFile() method is not exposed by the parser, then the client will depend on the parser to only invoke the 'parse()' method.

The above example is too simple. But hope you got my message.