0

I'm writing a method that should return the first item in an array belonging to a certain user. The class looks like this:

 public MailItem getNextMailItem(String who)
 {

         return mailbox.get(who).pollFirst();

 }

I need some sort of error handling in case the "who"-parameter is empty or null e.g

  if (who != null && who.length() != 0)

But what if that turns out to be false?

xsiand
  • 465
  • 1
  • 4
  • 10
  • 1
    This depends on your requirements. The most common strategies are returning null as your MailItem or throwing an exception. – jpvee Dec 11 '13 at 11:10
  • Of course! Somewhere in my confused mind I thought that returning null would give me an error. Thanks! – xsiand Dec 11 '13 at 11:13

3 Answers3

1

your if block is something like that

public MailItem getNextMailItem(String who) {
 MailItem item = null;
 if (who != null && who.length() != 0) {
    item = mailbox.get(who).pollFirst();
 } else {
  //show some error message or error log here 
 }
return item;
}

on filure your method will return null.

also read this Q&A

Community
  • 1
  • 1
Ashish Jagtap
  • 2,799
  • 3
  • 30
  • 45
0

Simple solution is to return null. On the other side, check for null and handle accordingly.

Girish
  • 16
  • 2
0

Returning null in the absence of a value would be an obvious solution:

public MailItem getNextMailItem(String who){
     MailItem mailItem = null;
     if (who != null && who.length() != 0){
        mailItem = mailbox.get(who).pollFirst();
     } 
     return mailItem;
}

But consider this:

If you communicate with null, your return value really is ambiguous. It can mean a lot of things. Instead, you could use Guava's Optional or the Null object pattern.

Using the Null pattern, you would define an instance that has a neutral behavior, possibly in your MailItem interface, and return it in case of the absence of a value:

public MailItem getNextMailItem(String who) {
    MailItem mailItem = null;
      if (who != null && who.length() != 0){
         mailbox.get(who).pollFirst();
      } else {
         mailItem = MailItem.NULL_ITEM;
      }
     return mailItem;
}

This way - unless an unexpected exception happens - you can always be sure that getNextMailItem returns a valid instance of MailItem.

Kai Sternad
  • 22,214
  • 7
  • 47
  • 42