Is there an alternative to hyper-indented code?

后端 未结 7 487
甜味超标
甜味超标 2020-12-16 22:36

I often run into code that has to perform lots of checks and ends up being indented at least five or six levels before really doing anything. I am wondering what alternativ

7条回答
  •  臣服心动
    2020-12-16 22:45

    You can get rid of some of the nesting by using guard clauses.

    public String myFunc(SomeClass input)
    {
        Object output = null;
    
        if(input == null) return "";
    
        SomeClass2 obj2 = input.getSomeClass2();
        if(obj2 == null) return "";
    
        SomeClass3 obj3 = obj2.getSomeClass3();
        if(obj3 == null || BAD_OBJECT.equals(obj3.getSomeProperty()))
        {
            return "";
        }
    
        SomeClass4 = obj3.getSomeClass4();
        if(obj4 == null) return "";
    
        int myVal = obj4.getSomeValue();
        if(BAD_VALUE == myVal) return "";
    
        String message = this.getMessage(myVal);
        if(MIN_VALUE <= message.length() &&
               message.length() <= MAX_VALUE)
        {
             //now actually do stuff!
             message = result_of_stuff_actually_done;
        }
    
        return output;
    }
    

    Change all of the return ""; statements that I used to illustrate the point to statements that throw a descriptive variety of Exception, though.

提交回复
热议问题