Is it acceptable to use exceptions instead of verbose null-checks?

前端 未结 9 2424
刺人心
刺人心 2020-12-28 21:51

I recenly encountered this problem in a project: There\'s a chain of nested objects, e.g.: class A contains an instance variable of class B, which in turns has an instance v

9条回答
  •  温柔的废话
    2020-12-28 22:14

    It is bad design if parentObject needs to know that A contains a B which contains a C wich contains.... That way, everything is coupled to everything. You should have a look at the law of demeter: http://en.wikipedia.org/wiki/Law_Of_Demeter

    parentObject should only call methods on its instance variable B. So, B should provide a method that allows for the decision, e.g.

    public class A {
      private B myB;
      //...
      public boolean isItValidToDoSomething(){
        if(myB!=null){
          return myB.isItValidToDoSomething();
        }else{
          return false;
        }
      }
    }
    

    Eventually, at the level of Z, the method has to return true.

    Imho, saving development time is never a reason for tolerating problems in the design. Sooner or later these problems will steal you more time than it would have taken to fix the problems in the first place

提交回复
热议问题