How to avoid null checking in Java?

后端 未结 30 3290
失恋的感觉
失恋的感觉 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:30

    Just don't ever use null. Don't allow it.

    In my classes, most fields and local variables have non-null default values, and I add contract statements (always-on asserts) everywhere in the code to make sure this is being enforced (since it's more succinct, and more expressive than letting it come up as an NPE and then having to resolve the line number, etc.).

    Once I adopted this practice, I noticed that the problems seemed to fix themselves. You'd catch things much earlier in the development process just by accident and realize you had a weak spot.. and more importantly.. it helps encapsulate different modules' concerns, different modules can 'trust' each other, and no more littering the code with if = null else constructs!

    This is defensive programming and results in much cleaner code in the long run. Always sanitize the data, e.g. here by enforcing rigid standards, and the problems go away.

    class C {
        private final MyType mustBeSet;
        public C(MyType mything) {
           mustBeSet=Contract.notNull(mything);
        }
       private String name = "";
       public void setName(String s) {
          name = Contract.notNull(s);
       }
    }
    
    
    class Contract {
        public static  T notNull(T t) { if (t == null) { throw new ContractException("argument must be non-null"); return t; }
    }
    

    The contracts are like mini-unit tests which are always running, even in production, and when things fail, you know why, rather than a random NPE you have to somehow figure out.

提交回复
热议问题