我有这个异常处理代码。如果它可以简化为方法而不是在主方法中全部使用它,我就会徘徊。或者,拥有单独的课程会更好吗?非常感谢
import java.util.Scanner;
import java.io.*;
class ReadWrite {
public static void main(String args[]) {
try {
File myFile = new File("fruits.txt");
Scanner sc = new Scanner(System. in );
FileWriter fw = new FileWriter(myFile, true);
PrintWriter pw = new PrintWriter(fw);
String fn = "";
while (!fn.equals("exit")) {
System.out.println("Please enter the fruit name or enter exit");
fn = sc.nextLine();
if (!fn.equals("exit")) {
pw.println(fn);
}
}
pw.close();
Scanner readFile = new Scanner(myFile);
int i = 1;
while (readFile.hasNextLine()) {
System.out.println(i + ": " + readFile.nextLine());
i++;
}
readFile.close();
} catch (Exception e) {
e.printStackTrace(); //shows all problems in list
}
}
}
答案 0 :(得分:1)
根据SOLID
单一责任原则 - >每一件事"应该承担单一责任。 所以简短的答案是肯定的,你可以而且你应该,答案很长:
class ReadWrite
{
public static void main(String args[])
{
DataRequester dataRequester = new DataRequester(new ConsolePrinter());
String myFileName = "fruits.txt";
FruitWriter fruitWriter = new FruitWriter();
FruitPrinter fruitPrinter = new FruitPrinter(new ConsolePrinter());
fruitWriter.writeFruits(dataRequester, myFileName);
fruitPrinter.printFruitsFrom(myFileName);
}
}
interface Printer
{
void print(String string);
}
class FileWriterFactory
{
public FileWriter createFrom(String path)
{
try
{
return new FileWriter(path, true);
} catch (IOException e)
{
throw new RuntimeException(e);
}
}
}
class ConsolePrinter implements Printer
{
@Override
public void print(String string)
{
System.out.println(string);
}
}
class DataRequester
{
private final Printer printer;
DataRequester(Printer printer)
{
this.printer = printer;
}
public void requestForDataOf(String type)
{
printer.print(String.format("Please enter the %s name or enter exit", type));
}
}
class FruitWriter{
public void writeFruits(DataRequester dataRequester, String myFileName)
{
FileWriter fw = new FileWriterFactory().createFrom(myFileName);
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(fw);
String fn = "";
while (shouldExit(fn))
{
dataRequester.requestForDataOf("fruit");
fn = sc.nextLine();
if (shouldExit(fn))
{
pw.println(fn);
}
}
pw.close();
}
private static boolean shouldExit(String fn)
{
return !fn.equals("exit");
}
}
class FruitPrinter{
private final Printer printer;
FruitPrinter(Printer printer)
{
this.printer = printer;
}
public void printFruitsFrom(String path){
Scanner readFile = new Scanner(path);
int line = 1;
while (readFile.hasNextLine())
{
printer.print(String.format("Line %s: %s", line, readFile.nextLine()));
line++;
}
readFile.close();
}
}
显然,这需要分成文件,每个文件的文件。
注意现在一切都变得清晰。
从阅读主要方法我理解应用程序,我确切知道除了它要做什么。
它写了水果。
并打印出来。
从何而来?去哪儿? 我不在乎。 如果我关心我会查看实施。
另外,请看打印机的分离。 我的水果打印机不知道他打印到哪里,他也不知道。 我给了他一台打印机,打印机知道如何打印,这就是最重要的。 如果明天我想使用文件打印机,我会改变这一行:
FruitPrinter fruitPrinter = new FruitPrinter(new ConsolePrinter());
到
FruitPrinter fruitPrinter = new FruitPrinter(new FilePrinter());
没有人会知道差异! 这是SOLID,OCP和DIP的另外两个原则,我建议你阅读它们。