Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Best practice for getter methods

 
Michele Dibenedetto
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49789
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the Ranch
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ooooh, I didn't even notice, welcome indeed!
 
Michele Dibenedetto
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your answer Jelle!

Ritchie
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic