为命令行界面组织命令的好方法是什么?

时间:2018-07-05 23:16:37

标签: java switch-statement command-line-interface tui

我在创建清晰简洁的代码时遇到了麻烦,该代码使我可以执行各种命令来执行各种不同的操作。因此,例如,在我正在使用的N型身体模拟器中,我想要的功能是用户可以输入诸如tele pos [x] [y] [z]tele celobj [celestial object name]之类的命令。

要做到这一点,我根据空格的位置将输入字符串分成多个令牌数组。然后,我使用一系列switch语句,以便在一个switch语句层中处理第一个单词(tele),然后在第二个单词(poscelobj)中处理第二层switch语句。然后,相应地处理下一个标记。在所有这些不同的层中,我检查用户是否输入了有效的单词数,以避免超出范围的异常。

我的代码可以正常工作,但是显然很难阅读并且过于复杂。我不是在寻找帮助自己的代码,而是一种用于组织命令系统或以最佳方式设置逻辑的概念性策略。

我已经包括了源代码,以防万一,但是我希望我的描述足够清楚。

public static void process(String cmd) {
    String tokenNotFound = "Token not recognized...";
    String notEnoughInfo = "Not enough info given. Please specify...";
    String unableToParse = "Unable to parse number...";

    String[] tokens = cmd.toLowerCase().split("\\s+");
    switch (tokens[0]) {
        case "close":
            run = false;
            break;
        case "toggle":
            if (tokens.length >= 2) {
                switch (tokens[1]) {
                    case "render":
                        render = !render;
                        System.out.println("Render setting set to " + render);
                        break;
                    case "physics":
                        updatePhysics = !updatePhysics;
                        System.out.println("Physics update setting set to " + updatePhysics);
                        break;
                    case "trails":
                        showTrails = !showTrails;
                        System.out.println("Show trails setting set to " + showTrails);
                        break;
                    case "constellations":
                        showConstellations = !showConstellations;
                        System.out.println("Show constellations setting set to " + showConstellations);
                        break;
                    default:
                        System.err.println(tokenNotFound);
                }
            } else
                System.err.println(notEnoughInfo);
            break;
        case "get":
            if (tokens.length >= 2) {
                switch (tokens[1]) {
                    case "fps":
                        System.out.println("FPS: " + realFPS);
                        break;
                    case "ups":
                        System.out.println("UPS: " + realUPS);
                        break;
                    case "cps":
                        System.out.println("CPS: " + realCPS);
                        break;
                    case "performance":
                        System.out.println("FPS: " + realFPS + " UPS: " + realUPS + " CPS: " + realCPS);
                        break;
                    case "time":
                        System.out.println(getTimestamp());
                        break;
                    case "celobj":
                        if (tokens.length >= 3) {
                            boolean objFound = false;
                            CelObj chosenObj = null;
                            for (CelObj celObj : physics.getCelObjs()) {
                                if (celObj.getName().toLowerCase().equals(tokens[2])) {
                                    objFound = true;
                                    chosenObj = celObj;
                                }
                            }

                            if (objFound) {
                                if (tokens.length >= 4) {
                                    switch (tokens[3]) {
                                        case "pos":
                                            Vec3d pos = chosenObj.getCelPos();
                                            System.out.println("POSITION: X= " + pos.x + " Y= " + pos.y + " Z= " + pos.z);
                                            break;
                                        case "vel":
                                            Vec3d vel = chosenObj.getCelVel();
                                            if (tokens.length >= 5 && tokens[4].equals("mag"))
                                                System.out.println("VELOCITY: V= " + vel.magnitude());
                                            else
                                                System.out.println("VELOCITY: X= " + vel.x + " Y= " + vel.y + " Z= " + vel.z);
                                            break;
                                        case "mass":
                                            System.out.println("MASS: M= " + chosenObj.getMass());
                                            break;
                                        case "radius":
                                            System.out.println("RADIUS: R= " + chosenObj.getRadius());
                                            break;
                                        default:
                                            System.err.println(notEnoughInfo);
                                    }
                                } else
                                    System.err.println(notEnoughInfo);
                            } else
                                System.err.println(tokenNotFound);
                        } else {
                            //Print list of celObjs
                            StringBuilder celObjNames = new StringBuilder("Celestial Objects: \n");
                            for (CelObj celObj : physics.getCelObjs()) {
                                celObjNames.append('\t').append(celObj.getName()).append('\n');
                            }
                            System.out.println(celObjNames.toString());
                        }
                        break;
                    default:
                        System.err.println(tokenNotFound);
                }
            } else
                System.err.println(notEnoughInfo);
            break;
        case "set":
            if (tokens.length >= 2) {
                switch (tokens[1]) {
                    case "cps":
                        if (tokens.length >= 3) {
                            try {
                                int newCPS = parseInt(tokens[2]);
                                realTime_to_simTime = newCPS * timeInc;
                                System.out.println("Target CPS set to " + newCPS);
                                System.out.println("The simulation time is " + realTime_to_simTime + " times the speed of real time");
                            } catch (Exception e) {
                                System.err.println(unableToParse);
                            }
                        } else
                            System.err.println(notEnoughInfo);
                        break;
                    case "scale":
                        if (tokens.length >= 3) {
                            try {
                                scale = parseFloat(tokens[2]);
                                System.out.println("Render object scale is now set to " + scale);
                            } catch (Exception e) {
                                System.err.println(unableToParse);
                            }
                        } else
                            System.err.println(notEnoughInfo);
                        break;
                    case "speed":
                        if (tokens.length >= 3) {
                            try {
                                speed = parseFloat(tokens[2]);
                                System.out.println("Speed is now set to " + speed);
                            } catch (Exception e) {
                                System.err.println(unableToParse);
                            }
                        } else
                            System.err.println(notEnoughInfo);
                        break;
                    case "record":
                        if (tokens.length >= 4) {
                            if (tokens[3].equals("period")) {
                                try {
                                    int newCPS = parseInt(tokens[2]);
                                    realTime_to_simTime = newCPS * timeInc;
                                    System.out.println("Target CPS set to " + newCPS);
                                    System.out.println("The recording period is now every " + realTime_to_simTime + " seconds");
                                } catch (Exception e) {
                                    System.err.println(unableToParse);
                                }
                            } else
                                System.err.println(tokenNotFound);

                        } else
                            System.err.println(notEnoughInfo);
                        break;
                    case "center":
                        if (tokens.length >= 3) {
                            boolean objFound = false;
                            CelObj chosenObj = null;
                            for (CelObj celObj : physics.getCelObjs()) {
                                if (celObj.getName().toLowerCase().equals(tokens[2])) {
                                    objFound = true;
                                    chosenObj = celObj;
                                }
                            }

                            if (objFound) {
                                centerCelObj = chosenObj;
                                System.out.println(chosenObj.getName() + " has been set as the center");
                            } else
                                System.err.println(tokenNotFound);
                        } else
                            System.err.println(notEnoughInfo);
                        break;
                    default:
                        System.err.println(tokenNotFound);
                }
            } else
                System.err.println(notEnoughInfo);
            break;
        case "create":
            //TODO:
            break;
        case "uncenter":
            centerCelObj = null;
            System.out.println("There is currently no center object");
            break;
        case "tele":
            if (tokens.length >= 2) {
                switch (tokens[1]) {
                    case "pos":
                        if (tokens.length >= 5) {
                            try {
                                double x = parseDouble(tokens[2]);
                                double y = parseDouble(tokens[3]);
                                double z = parseDouble(tokens[4]);

                                Vec3f cameraPos = new Vec3f((float) x, (float) y, (float) z);

                                //If camera is locked to an object, then translating the camera will only
                                //do so with respect to that planet
                                //Hence, the camera is translated back to world coordinates by translating it
                                //the negative of its locked celObj position vector
                                if (camera.getLockedCelObj() != null) {
                                    cameraPos.translate(
                                            new Vec3f(
                                                    camera.getLockedCelObj().getCelPos()
                                            ).negate()
                                    );
                                }

                                camera.setPosition(multiply(worldunit_per_meters, cameraPos));
                                System.out.println("The camera position has been set to X= " + x + " Y= " + y + " Z= " + z);
                            } catch (Exception e) {
                                System.err.println(unableToParse);
                            }
                        } else
                            System.err.println(notEnoughInfo);
                        break;
                    case "celobj":
                        if (tokens.length >= 3) {
                            boolean objFound = false;
                            CelObj chosenObj = null;
                            for (CelObj celObj : physics.getCelObjs()) {
                                if (celObj.getName().toLowerCase().equals(tokens[2])) {
                                    objFound = true;
                                    chosenObj = celObj;
                                }
                            }

                            if (objFound) {
                                Vec3f celObjPos = new Vec3f(chosenObj.getCelPos());
                                Vec3f cameraPos = add(celObjPos, new Vec3f(0, (float) chosenObj.getRadius() * 2, 0));

                                //If camera is locked to an object, then translating the camera will only
                                //do so with respect to that planet
                                //Hence, the camera is translated back to world coordinates by translating it
                                //the negative of its locked celObj position vector
                                if (camera.getLockedCelObj() != null) {
                                    cameraPos.translate(
                                            new Vec3f(
                                                    camera.getLockedCelObj().getCelPos()
                                            ).negate()
                                    );
                                }

                                //Make player 1 planet radius away from surface
                                camera.setPosition(multiply(worldunit_per_meters, cameraPos));
                                camera.setLookAt(multiply(worldunit_per_meters, celObjPos));

                                System.out.println("The camera position has been set to X= " + cameraPos.x + " Y= " + cameraPos.y + " Z= " + cameraPos.z);
                            } else
                                System.err.println(tokenNotFound);
                        } else
                            System.err.println(notEnoughInfo);
                        break;
                    default:
                        System.err.println(tokenNotFound);
                }
            } else
                System.err.println(notEnoughInfo);
            break;
        case "lock":
            if (tokens.length >= 2) {
                boolean objFound = false;
                CelObj chosenObj = null;
                for (CelObj celObj : physics.getCelObjs()) {
                    if (celObj.getName().toLowerCase().equals(tokens[1])) {
                        objFound = true;
                        chosenObj = celObj;
                    }
                }

                if (objFound) {
                    camera.setLockedCelObj(chosenObj);
                    camera.setPosition(new Vec3f(0, 0, 0));
                    System.out.println("The camera has been locked to " + chosenObj.getName());
                    System.out.println("Type 'unlock' to revert back to unlocked status");
                } else
                    System.err.println(tokenNotFound);
            } else
                System.err.println(notEnoughInfo);
            break;
        case "unlock":
            String celObjName = camera.getLockedCelObj().getName();
            //If camera is locked to an object, then translating the camera will only
            //do so with respect to that planet
            //Hence, the camera is translated back to world equivalent of where it is in
            //that celObj's space by translating it the celObj's position
            camera.setPosition(
                    add(
                            multiply(worldunit_per_meters,
                                    (new Vec3f(camera.getLockedCelObj().getCelPos()))),
                            camera.getPosition()
                    )
            );
            camera.setLockedCelObj(null);
            System.out.println("The camera has been unlocked from " + celObjName);
            Vec3f pos = camera.getPosition();
            System.out.println("The camera position has been set to X= " + pos.x + " Y= " + pos.y + " Z= " + pos.z);
            break;
        case "lookat":
            if (tokens.length >= 3) {
                switch (tokens[1]) {
                    case "celobj":
                        boolean objFound = false;
                        CelObj chosenObj = null;
                        for (CelObj celObj : physics.getCelObjs()) {
                            if (celObj.getName().toLowerCase().equals(tokens[2])) {
                                objFound = true;
                                chosenObj = celObj;
                            }
                        }

                        if (objFound) {
                            camera.setLookAt(new Vec3f(multiply(worldunit_per_meters, chosenObj.getCelPos())));
                            System.out.println("The camera is now looking at " + chosenObj.getName());
                        } else
                            System.err.println(tokenNotFound);
                        break;
                }
            } else
                System.err.println(notEnoughInfo);
            break;
        default:
            System.err.println(tokenNotFound);
    }
}

2 个答案:

答案 0 :(得分:0)

您的直觉是正确的。您所拥有的代码可以真正地从以某种方式分解为较小的片段中受益。做到这一点的一种好方法是使其更受数据驱动。编码一长串命令的一种方法是在switch语句中,但是问题是该语句随着您拥有的命令越来越多而变得越来越长。数据驱动方法将命令名称和其后的代码视为数据,并将命令列表与解析并执行命令的代码分开。

让我们从一个代表命令处理程序的简单接口开始。这个函数会先赋予命令参数,然后执行命令所要做的任何事情。

public interface CommandHandler {
    public void handle(List<String> arguments);
}

然后让process()函数成为数据驱动的函数。现在,让我们处理前两个命令“ close”和“ toggle”。我们将从简单开始,看看这个想法是否有意义,然后在高层了解我们想做什么之后充实实现。

我们将创建命令名称到其处理程序的映射。这将为我们提供紧凑的命令列表,其中每个命令后面的代码分为单独的回调函数。如果您不熟悉它,则Commands::close是方法参考。它为我们提供了一个CommandHandler对象,该对象调用了方法Commands.close(),稍后将对其进行定义。

public static void process(String input) {
    Map<String, CommandHandler> commands = new HashMap<>();
    commands.put("close",  Commands::close);
    commands.put("toggle", Commands::toggle);

    List<String> tokens = Arrays.asList(input.toLowerCase().split("\\s+"));
    process(tokens, commands);
}

这看起来不错。它又短又甜。它将输入字符串拆分为标记,但这就是它所做的全部工作。其余的推迟到第二个process()方法。让我们现在写:

public static void process(List<String> tokens, Map<String, CommandHandler> commands) {
    String command = tokens.get(0);
    List<String> arguments = tokens.subList(1, tokens.size());

    CommandHandler handler = commands.get(command);

    if (handler != null) {
        handler.handle(arguments)
    }
}

这是命令解析逻辑的核心。它在映射中查找命令,如果找到一个,则执行相应的处理程序。很好的是,此方法对任何特定命令一无所知。这都是非常通用的。

它还设置为支持子命令。请注意,它是如何获取令牌列表的?以及如何将参数保存在单独的子列表中?这样做意味着不仅可以为顶级命令调用它,还可以为诸如“渲染”之类的子命令调用它。

难题的最后一步是定义每个命令处理程序。我已经将它们放在自己的班级中,但是您不必这样做。这些全都可以是您原始类中的方法(我只是不知道您叫它的名字就是全部)。

public class Commands {
    public static void close(List<String> arguments) {
        run = false;
    }    

    public static void toggle(List<String> arguments) {
        if (arguments.length == 0) {
            System.err.println(notEnoughInfo);
            return;
        }

        Map<String, CommandHandler> subCommands = new HashMap<>();

        subCommands.put("render", arguments -> {
            render = !render;
            System.out.println("Render setting set to " + render);
        });

        subCommands.put("physics", arguments -> {
            updatePhysics = !updatePhysics;
            System.out.println("Physics update setting set to " + updatePhysics);
        });

        subCommands.put("trails", arguments -> {
            showTrails = !showTrails;
            System.out.println("Show trails setting set to " + showTrails);
        });

        subCommands.put("constellations", arguments -> {
            showConstellations = !showConstellations;
            System.out.println("Show constellations setting set to " + showConstellations);
        });

        process(arguments, subCommands);
    }
}

toggle()展示了子命令解析。就像上面的代码一样,它创建子命令的映射并注册其名称和处理程序。就像顶上一样,它调用与以前相同的process()函数。

这一次,因为处理程序非常简单,所以没有必要将它们分解为单独的命名函数。我们可以使用匿名lambda来内联注册处理程序。像Commands::close之前所做的一样,arguments -> { code }创建一个CommandHandler内联。

答案 1 :(得分:0)

考虑使用getopt

 Getopt g = new Getopt("testprog", argv, "ab:c::d");
 //
 int c;
 String arg;
 while ((c = g.getopt()) != -1)
   {
     switch(c)
       {
          case 'a':
          case 'd':
            System.out.print("You picked " + (char)c + "\n");
            break;
            //
          case 'b':
          case 'c':
            arg = g.getOptarg();
            System.out.print("You picked " + (char)c + 
                             " with an argument of " +
                             ((arg != null) ? arg : "null") + "\n");
            break;
            //
          case '?':
            break; // getopt() already printed an error
            //
          default:
            System.out.print("getopt() returned " + c + "\n");
       }
   }

related

相关问题