I've been coding in java for a few years now, and I really like the idea of not using null when possible, which for the most part is not too difficult, but I keep coming back to the same instance where I can't decide if its better to use a ObjectNotFoundException or just return null. Any body have any thoughts on the best practice here?
Say you have some email subscriptions stored in a database, which you access via a unique key (code):
public EmailSubscriptionModel getSubscriptionByCode(final String code){
//go get a list of email subscriptions from DB matching code
if({list is not empty}){
return list.get(0);
}else{
return null;
}
}
public void subscribe(final String code){
EmailSubscriptionModel subscription = getSubscriptionByCode(code);
if(subscription != null){
//do subscription
}
}
The only way I can think of to to avoid this null check is to throw an ObjectNotFoundException
in the getSubscriptionByCode()
method in which case we'd have to use a try/catch to catch the error like so:
public EmailSubscriptionModel getSubscriptionByCode(final String code)
throws ObjectNotFoundException{
//go get a list of email subscriptions from DB matching code
if({list is empty}){
throw new ObjectNotFoundException();
}
return list.get(0);
}
public void subscribe(final String code){
try{
EmailSubscriptionModel subscription = getSubscriptionByCode(code);
//do subscription
}catch(ObjectNotFoundException e){
//just move on
}
}
Is there a reason this would be preferable to the former? or is it just a style choice?