首页 > 解决方案 > 如何重构深度嵌套的函数?

问题描述

我的代码目前如下所示:

If (case = 1)
{
    If (option = 1)
    {
        If (otherOption = 1)
            ;do something
        else if (otherOption = 2)
            ;do something
        else if (otherOption = 3)
            ;do something
    }
    else
    {
        If (otherOption = 1)
            ;do something
        else if (otherOption = 2)
            ;do something
        else if (otherOption = 3)
            ;do something
    }
}

else if (case = 2)
{
    If (option = 1)
    {
        If (otherOption = 1)
            ;do something
        else if (otherOption = 2)
            ;do something
        else if (otherOption = 3)
            ;do something
    }
    else
    {
        If (otherOption = 1)
            ;do something
        else if (otherOption = 2)
            ;do something
        else if (otherOption = 3)
            ;do something
    }
}

else if (case = 3)
{
    If (option = 1)
    {
        If (otherOption = 1)
            ;do something
        else if (otherOption = 2)
            ;do something
        else if (otherOption = 3)
            ;do something
    }
    else
    {
        If (otherOption = 1)
            ;do something
        else if (otherOption = 2)
            ;do something
        else if (otherOption = 3)
            ;do something
    }
}

显然可怕且难以维护。我想在此之上添加另一个超级 If 语句,它将这棵树拆分 6 次。每个 ;do something 都执行一行代码。

关于如何重构这个怪物的任何帮助?我写了很多看起来像这样的代码,我每次都害怕使用它。我需要一种新的方法来解决这些问题。扩展此代码的功能需要大量工作。

标签: if-statementnestedrefactoringstatements

解决方案


即使您没有指定应用程序的上下文,这似乎也是一个可以利用Strategy Pattern应用程序的场景。

您发布的代码可以设置为Context对象,负责控制外部 if-else 语句的更高级别条件。在 if-else 语句的每个块中,可以使用ConcreteStrategy对象(通常实现Strategy接口)
加载特定行为。

这种模式可以重复用于内部 if-else 块。

例子

考虑一个角色在 2D 地图周围移动的游戏。根据其生命指标(例如 0-200),如果他分别处于疲倦、正常或超级状态,它可以移动 2、5、8 格。

Character对象的行为类似于“策略模式的上下文”,并且他负责哪种MoveStrategy适合该情况。赋予正确的MoveStrategy对象并通过转发方法move()到 Character 的move()方法来调用.

示例的 Java 实现提示:

public class Character{

    private int life=100;
    private int x=0 
    private int y=0; 
    private MoveStrategy strategy=new DefaultStrategy();


    public int getLife(){
        return life;
        }

        public void setLife(int value){
        this.life=value;
        }

    public void move(){
        if(life<30)
            strategy=new TiredStrategy();
        else if(life > 100)
            strategy=new SuperStrategy();
        else
            strategy=new DefaultStrategy();


        strategy.move();

    }
}



public interface MoveStrategy{

    public abstract void move();

}

public DefaultStrategy implements MoveStrategy{

    public void move(){
        System.out.println("Move character of 5 tiles");
    }
}

public TiredStrategy implements MoveStrategy{

    public void move(){
        System.out.println("Move character of 2 tiles");
    }
}

public SuperStrategy implements MoveStrategy{

    public void move(){
        System.out.println("Move character of 8 tiles");
    }
}

推荐阅读