有超级缩进代码的替代方法吗? [英] Is there an alternative to hyper-indented code?

查看:121
本文介绍了有超级缩进代码的替代方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常遇到的代码,必须执行大量的检查,最后缩进至少五或六个级别,才真正做任何事情。我想知道有什么替代方案存在。

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 alternatives exist.

下面我已经发布了一个例子我在说什么(这不是实际的生产代码,只是我想到的东西

Below I've posted an example of what I'm talking about (which isn't actual production code, just something I came up with off the top of my head).

public String myFunc(SomeClass input)
{
    Object output = null;

    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)
                        {
                            //now actually do stuff!
                            message = result_of_stuff_actually_done;
                        }
                    }
                }
            }
        }
    }
    return output;
}


推荐答案

请参阅展开箭头代码以获取帮助。



  1. 用guard
    子句替换条件。

  2. 将条件块分解为
    独立函数。

  3. 将负数支票转换为
    正数支票。


这篇关于有超级缩进代码的替代方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆