3

I have a class that holds a couple of byte arrays, some could be empty some not. And I want to return the first non null array (if there is one) or null if there isn't. But the code just seems so redundant and ugly.

public byte[] getFirstPhoto() {
    if (photo1 != null) {
        return photo1;
    }       
    if (photo2 != null) {
        return photo2;
    }
    if (photo3 != null) {
        return photo3;
    }
    if(videoThumbnail != null){
        return videoThumbnail;
    }
    return null;
}

Is there anyway to clean that up, or not really?

John
  • 1,808
  • 7
  • 28
  • 57

1 Answers1

4

Yes. Write a method something like this:

public byte[] firstNonNull(byte[]... arrays) {
    for (byte[] array : arrays) {
        if (array != null)
            return array;
    }
    return null;
}

Then call this function passing in your four arrays in the proper order.

BPS
  • 1,606
  • 20
  • 37