File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Best practice for getter methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Best practice for getter methods" Watch "Best practice for getter methods" New topic
Author

Best practice for getter methods

Michele Dibenedetto
Greenhorn

Joined: Oct 13, 2010
Posts: 5
In a simple java class where some getter methods return object fields which is the better practice for handling null fields?
Throw an exception? Simply return null and let the caller check the returned value? Something else?

The first choice requires that every invocation of the getter has to be surrounded by a try-catch and this makes my code
grow fast and became more difficult to read; the second choice increase the possibility to have somewhere a null pointer
exception because the caller forgot to check returned value.

Anyway I don't think that to throw an exception in case of missing value is correct because there has not been an error
in method execution, simply the information provided by the getter is "the absence of information" about the requested field

Thanks for help,
Michele
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1821
    
    7

Right, if a "missing" or null value for a field would violate the class invariant, you should throw an Exception at the time the value is set (setter / constructor), but certainly not from inside a getter method. Otherwise, you could simply return a null reference, and use the JavaDoc comment to state that a caller should expect and be able to handle it. Alternatively, if you don't like throwing null references around, you could have a look at the Null Object pattern.


Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39784
    
  28
And welcome to the Ranch
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1821
    
    7

Ooooh, I didn't even notice, welcome indeed!
Michele Dibenedetto
Greenhorn

Joined: Oct 13, 2010
Posts: 5
Thanks for your answer Jelle!

Ritchie
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Best practice for getter methods