我开始学习这本书:头第一设计模式。当我在书中尝试不同的程序时,我会在这个演示应用程序中编译它们。下面是其驱动程序功能的代码。有谁能指导我在这个驱动程序代码中对程序进行任何改进(与样式、编程、格式化、如何测试、尝试/捕获/最后或抛出异常或诸如此类的东西有关)?
package com.aviralgarg;
import java.util.Scanner;
import static com.aviralgarg.strategy.Main.runDuckSimulator;
public class Main {
public static void main(String[] args) {
try {
demoLoop();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.err.println("Something went horribly wrong!");
}
}
private static void demoLoop() {
while (true) {
showOptions();
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
switch (option) {
case 0 -> System.exit(0);
case 1 -> showDesignPrinciples();
case 2 -> runDuckSimulator();
default -> System.err.println("Please select a valid option.");
}
showHorizontalLine();
}
}
private static void showHorizontalLine() {
System.out.println("------------------------------------------------------------------------------------");
}
private static void showOptions() {
System.out.println("\nPick one of the following options:" +
"\n\t1. Show design principles" +
"\n\t2. Strategy pattern - Run the Duck Simulator" +
"\n\t0. Exit");
}
private static void showDesignPrinciples() {
System.out.println("Design Principles:" +
"\n1. Identify the aspects of your application that vary and separate them from what stays the same." +
"\n2. Program to an interface, not an implementation." +
"\n3. Favor composition over inheritance." +
"\n\n");
}
}可以在这里找到整个存储库:https://github.com/aviral-garg/design-patterns。对其余这些职能的任何改进也将不胜感激。或者我可以问一个单独的问题,因为策略设计模式被分割成几个不同的文件,并且从这个驱动程序代码中抽象出来。
发布于 2020-06-05 19:53:28
仅仅捕捉到这样的每一个可能的异常并不被认为是一个好的实践。您应该始终指定哪些异常是可能的,并且应该被捕获。在这种特殊情况下,根本不需要try-catch-statement,因为您已经捕获了demoLoop中所有可能的异常:
public static void main(String[] args) {
demoLoop();
}你是否信任用户做出正确的输入?如果用户确实输入了一个字符串而不是一个数字,您的程序就会崩溃。您可以使用以下代码片段解决此问题:
private static void demoLoop() {
Scanner scanner = new Scanner(System.in);
showOptions();
int option;
while(true) {
try {
option = scanner.nextInt();
if(option > 2 || option < 0) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0, 1 or 2!");
scanner.nextLine();
}
}
}(别忘了去import java.util.InputMismatchException;)
我也不喜欢使用开关箱-statement的方式,但这可能只是品味问题。我更喜欢标准的方式:
switch (option) {
case 0 :
System.exit(0);
break;
case 1 :
showDesignPrinciples();
break;
case 2 :
runDuckSimulator();
break;
default :
System.err.println("Please select a valid option.");
}https://codereview.stackexchange.com/questions/243351
复制相似问题