Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Null vs ObjectNotFoundException in java

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?

like image 939
Ryan Avatar asked Mar 15 '23 18:03

Ryan


1 Answers

First of all, exceptions are for the exceptional - you should not throw an exception if something like a subscriber isn't found. It's no big deal. Consider a use case of someone wanting to check if they subscribed - if the answer is no (ie their subscription was not found) its not an exception.

Use exceptions to tell the caller that a situation was encountered that can not be handled and the problem of handling it is being delegated to the caller.

Returning null is fine for java 7.

Use Optional for java 8+ for a cleaner API.

like image 144
Bohemian Avatar answered Mar 23 '23 00:03

Bohemian