java - 哪个更好?在每个其他函数定义的末尾使用 while 循环或调用 main 函数

标签 java while-loop

<分区>

MainScreen() {
    DisplayUI();
    GetInput();
}
DisplayUI {
    // prints press 1 for this 2 for that etc...
}
GetInput() {
    // Gets input and calls the next approprite function according to that input e.g 1 for login etc...
    // e.g 
    if (input == 1) {
    Login();
    }
    .
    .
    .
    if (input == x) {
    somefunc();
    }
    // if the user enters an input that is not accounted for call this function
    MainScreen();
}

Login() {
    // do some stuff
    MainScreen();
}
somefunc() {
    // do some stuff
    MainScreen();
}

main {
    MainScreen();
}

使用上述方法是否有任何缺点(在每个函数实现的末尾都有 MainScreen();?)?

在此之上(使用 while 循环并从每个函数的末尾删除 MainScreen();)

哪个更好?无论哪种情况,我都想无限期地运行我的程序。我使用了上述方法并且我的程序运行完美,是否需要更改我的代码?

main {
    while(true){
        MainScreen();   // 
    }
}

最佳答案

使用循环肯定更好。

在每个函数的末尾都有一个 MainScreen(); 违反了 DRY 原则(例如,如果您决定更改该函数名称,您将必须找到放置该语句的所有位置) .

此外,不需要递归,所以不要使用它。

关于java - 哪个更好?在每个其他函数定义的末尾使用 while 循环或调用 main 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21572056/

相关文章:

c - 当 'Enter' 时结束 while 循环

java - 试图用开关盒内的开关盒打破 while 循环

c - 变量周围的运行时检查失败堆栈已损坏

java - Java 中 Jazzy 库的 Aspell 字典

java - Hashmap比较运行时间

linux - 在 bash 中不工作循环

java - while(true) 和集合

Java Swing keyEvent 与 keyPressed/keyReleased - 不同的键代码?

c# - 请帮助我为我的本科项目选择语言和框架

java - Spring-Boot:依赖注入(inject)取决于配置(和使用接口(interface))