Is there an alternative to hyper-indented code?

后端 未结 7 471
甜味超标
甜味超标 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 23:11

    If you don't need to process stop, don't embed.

    For example, you can do:

    if(input == null && input.getSomeClass2() == null && ...)
        return null;
    
    // Do what you want.
    

    Assuming you're using a language like Java that orders the conditionals.

    Alternatively you could:

    if(input == null && input.getSomeClass2() == null)
        return null;
    
    SomeClass2 obj2 = input.getSomeClass2();
    if(obj2 == null)
        return null;
    
    ...
    
    // Do what you want.
    

    For more complex cases.

    The idea is to return from the method if you don't need to process. Embedding in a large nested if is almost impossible to read.

    0 讨论(0)
提交回复
热议问题