How to avoid null checking in Java?

后端 未结 30 3331
失恋的感觉
失恋的感觉 2020-11-21 04:43

I use object != null a lot to avoid NullPointerException.

Is there a good alternative to this?

For example I often use:



        
30条回答
  •  我寻月下人不归
    2020-11-21 05:16

    1. Never initialise variables to null.
    2. If (1) is not possible, initialise all collections and arrays to empty collections/arrays.

    Doing this in your own code and you can avoid != null checks.

    Most of the time null checks seem to guard loops over collections or arrays, so just initialise them empty, you won't need any null checks.

    // Bad
    ArrayList lemmings;
    String[] names;
    
    void checkLemmings() {
        if (lemmings != null) for(lemming: lemmings) {
            // do something
        }
    }
    
    
    
    // Good
    ArrayList lemmings = new ArrayList();
    String[] names = {};
    
    void checkLemmings() {
        for(lemming: lemmings) {
            // do something
        }
    }
    

    There is a tiny overhead in this, but it's worth it for cleaner code and less NullPointerExceptions.

提交回复
热议问题