Throw an exception or return null

If I have a function below with two options

private MyObject findBlank() {
    for (int i = 0; i < pieces.length; i++) {
        if(pieces[i].isBlank()){
            return pieces[i];
        }
    }
    return null;
}

private MyObject findBlank() {
    for (int i = 0; i < pieces.length; i++) {
        if(pieces[i].isBlank()){
            return pieces[i];
        }
    }
    throw new NoSuchFieldError("No blank piece found!");
}

From this method, I know that it should always return an object , one of the “pieces” is always equal isBlank() == true, the return null at the end is just to please the compiler. Since this is the case, and my code will not work anyway if it returns null, is it right to do this to throw an exception?

My parameters:

  • return null and the application will get a NullPointerException in some edge case
  • returns null and ends using the method with (myObject! = null) checks
  • introduce an exception that will explode at runtime

, , ? .. , . "", , ( ). , null, ?

, , , ?

+5
10

, ,

  • , - , (.. null)?
  • , null?
  • , ?

2 3, , 2 3 . 1 , . NPE , , null. , , .

, , - , , , . null , , - .

+4

, , ?

, . -, , , null.

+10
+4

, , , , .

, : NULLPointerException: 1. 2.

, null , .

return nullObject ( null) , - , : 1. , nullObject, / . 2. , , .

+1

null

NullPointerException -
.

, pieces[i].isBlank(), IllegalStateException

.

0

, . ( 2sd )

() .

0

Maybe ( Option), .

Java.

:

private Option<MyObject> findBlank() {
    for (int i = 0; i < pieces.length; i++) {
        if(pieces[i].isBlank()){
            return Option.some(pieces[i]);
        }
    }
    return Option.none();
}

Sidenote:

findBack , , .

, Java .

, pieces fj.data.List. :

private Option<MyObject> findBlank() {
  return pieces.find(new F1<MyObject, Boolean>() {
    public Boolean f(MyObject p) {
      return p.isBlank();
    }
  });
}

:

, . IntelliJ IDEA " " .

0

, .

Provide an object as a surrogate for the lack of an object of a given type. The Null Object provides intelligent do nothing behavior, hiding the details from its collaborators

null. . , , null , Null object, , .

. , , .

public class CustomerFactory {

  public static final String[] names = {"Rob", "Joe", "Julie"};

  public static AbstractCustomer getCustomer(String name){   
    for (int i = 0; i < names.length; i++) {
       if (names[i].equalsIgnoreCase(name)){
         return new RealCustomer(name);
       }
    }
    return new NullCustomer();
  }
}
0

, , performance , , null

:

class Main {
    public static void main(String[] args) {
        testException();
        testNull();
    }

    public static void testException() {
        long st = System.currentTimeMillis();
        for(int i=0;i<10000000;i++) {
            try{
                exp();
            } catch(Exception e) {

            }
        }
        long et = System.currentTimeMillis();
        System.out.println("Time taken with exceptions : "+(et-st));
    }

    public static void testNull() {
        long st = System.currentTimeMillis();
        for(int i=0;i<10000000;i++) {
            returnNull();
        }
        long et = System.currentTimeMillis();
        System.out.println("Time taken with null : "+(et-st));
    }

    public static void exp() throws Exception {
        throw new Exception();
    }

    public static Object returnNull() {
        return null;
    }
}

:

Time taken with exceptions : 7526
Time taken with exceptions : 5

throwing , , , .

/.

0

, , . :

  1. , , , , .

  2. , , , , , , , - .

, :

private MyObject findBlankOrNull() {
    for (int i = 0; i < pieces.length; i++) {
        if(pieces[i].isBlank()){
            return pieces[i];
        }
    }
    return null;
}

private MyObject findBlankOrFail() throws Exception {
    MyObject obj = findBlankOrNull();
    if (obj != null) {
        return obj;
    }
    throw new NoSuchFieldError("No blank piece found!");
}

Note that a version OnFailcan always be created by calling another, and then throwing an exception instead of returning a null value. Essentially, what you are doing is inserting an exceptional value instead of a return null value, to ensure that the null value is not returned, and that you do not need code to check for a null value on the calling site.

I made a blog post on this topic: Return Zero or Exception? this covers it in a bit more detail.

0
source

All Articles