Is there an alternative to hyper-indented code?

后端 未结 7 469
甜味超标
甜味超标 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:57

    if it's just a readability issue you could make it clearer by moving the nesting to another method. Additionally convert to guard style if you like.

    public String myFunc(SomeClass input)
    {
        Object output = null;
    
        if (inputIsValid(input))
        {
          //now actually do stuff!
          message = result_of_stuff_actually_done;
        } 
    
        return output;
    }
    
    
    private bool inputIsValid(SomeClass input)
    {
    
        // *****************************************
        // convert these to guard style if you like   
        // ***************************************** 
        if(input != null)
        {
            SomeClass2 obj2 = input.getSomeClass2();
            if(obj2 != null)
            {
                SomeClass3 obj3 = obj2.getSomeClass3();
                if(obj3 != null && !BAD_OBJECT.equals(obj3.getSomeProperty()))
                {
                    SomeClass4 = obj3.getSomeClass4();
                    if(obj4 != null)
                    {
                        int myVal = obj4.getSomeValue();
                        if(BAD_VALUE != myVal)
                        {
                            String message = this.getMessage(myVal);
                            if(MIN_VALUE <= message.length() &&
                               message.length() <= MAX_VALUE)
                            {
                                return true;
                            }
                        }
                    }
                }
            }
        }
        return false;
    }
    

提交回复
热议问题