This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
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


Win a copy of Java 8 in Action this week in the Java 8 forum!
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: 1667
    
    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: 36599
    
  16
And welcome to the Ranch
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1667
    
    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
 
Similar Threads
rant on throwing exceptions
Check precondition in methods
Exception Handling(Checked/Unchecked)
invalid method declaration; return type required
should a method return null anytime?