java 如何重构这段混乱的代码

jgovgodb  于 2023-02-21  发布在  Java
关注(0)|答案(2)|浏览(128)

我需要重写这段代码,使它更漂亮一些。它从config.txt文件中读取行,并根据文件的内容设置变量。如您所见,代码在很多方面都很难看。2有很多重复的代码,程序检查文件内容的方式也不是很优雅(它可能应该迭代各行,而不是检查文件是否包含特定文本)总的来说,我认为避免有一堵巨大的if/else块墙会很好,它实际上继续向下延伸,但我觉得没必要把它都包括进去。
所有的程序代码都是用一个main方法编写的,我想创建一些类。我想创建一个Config类,它应该处理从配置文件中阅读,它应该有一个行列表(可能是行对象?)并按顺序处理它们。我最近一直在阅读有关Strategy patternCommand pattern的内容,并希望将类似内容应用到本例中。但是我不确定这些在这里是否合适。如果任何有经验的人对此有任何意见,我将不胜感激!

...
    try {
        reader = new BufferedReader(new FileReader(pathToConfig));
        line = reader.readLine();
        while(line!=null){
            if(line.contains("//")|| line.equals(""));
            else{
                if(line.contains("inputFolderPath"))    {
                    pathToFolder=line.split("=")[1];
                }
                else if(line.contains("defaultOutputPath")){
                    defaultOutputPath=line.split("=")[1];
                }
                else if(line.contains("checkStyleAttribute")&&!line.contains("Path")){
                    lineAfterSplit=line.split("=")[1];
                    checkStyle=Boolean.parseBoolean(lineAfterSplit);
                    errorListStyleAttribute=new ArrayList<String>();
                }
                else if(line.contains("checkXrefAndNormalLinks")&&!line.contains("Path")){
                    lineAfterSplit=line.split("=")[1];
                    checkXref=Boolean.parseBoolean(lineAfterSplit);
                    errorListXref = new ArrayList<String>();
                }
                else if(line.contains("checkThatAllTopicsHaveConceptKeywords")&&!line.contains("Path")){
                    lineAfterSplit=line.split("=")[1];
                    checkThatAllTopicsHaveConceptKeywords=Boolean.parseBoolean(lineAfterSplit);
                    errorListConceptKeywords=new ArrayList<String>();
                }
                else if(line.contains("checkThatAllTopicsHaveIndexKeywords")&&!line.contains("Path")){
                    lineAfterSplit=line.split("=")[1];
                    checkThatAllTopicsHaveIndexKeywords=Boolean.parseBoolean(lineAfterSplit);
                    errorListIndexKeywords=new ArrayList<String>();
                }
                else if(line.contains("checkForNoUIElementsInHeadings")&&!line.contains("Path")){

                    lineAfterSplit=line.split("=")[1];
                    checkForNoUIElementsInHeadings=Boolean.parseBoolean(lineAfterSplit);
                    errorListUiElements=new ArrayList<String>();
                }
                else if(line.contains("whatElementToCheckForStyle")){
                    tag=line.split("=")[1];
                    if(tag.charAt(0)=='['){
                        tag=tag.substring(1, tag.length()-1);
                        String[] tags = tag.split(",");
                        for(int i=0;i<tags.length;i++){
                            tagsToCheck.add(tags[i]);
                        }
                    }

                    else if(tag.equals("all")){
                        checkEveryTag=true;
                    }
                    else{
                        tagsToCheck.add(tag);
                    }
                }
                else if(line.contains("checkForProductNamesWithoutDNTTag")&&!line.contains("Path")){
                    lineAfterSplit=line.split("=")[1];
                    checkForProductNamesWithoutDNTTag=Boolean.parseBoolean(lineAfterSplit);
                    errorProductNamesWithoutDNTTag=new ArrayList<String>();
                }
     ... and it just goes on
z9zf31ra

z9zf31ra1#

正如我所看到的,你的大多数代码都在做重复性的工作(检查like是否有一些文本,并在上面执行一些操作)。我建议你创建可插入的matchAndPerform方法。即将字符串匹配和相关的方法调用封装到一个类(策略模式)中,并有一些类,你可以在其中动态注册和删除这些matcher对象。
策略模式示例:

public class Context {
   private Strategy strategy;
   public Context(Strategy strategy){
      this.strategy = strategy;
   }
   public int executeStrategy(int num1, int num2){
      return strategy.doOperation(num1, num2);
   }
}
public class OperationMultiply implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 * num2;
   }
}
vulvrdjw

vulvrdjw2#

well, I hope this helps

    try (BufferedReader reader = new BufferedReader(new FileReader(pathToConfig))) {
    String line;
    while ((line = reader.readLine()) != null) {
        if (line.contains("//") || line.isEmpty()) {
            continue;
        }
        String[] parts = line.split("=", 2);
        String key = parts[0].trim();
        String value = parts[1].trim();
        switch (key) {
            case "inputFolderPath":
                pathToFolder = value;
                break;
            case "defaultOutputPath":
                defaultOutputPath = value;
                break;
            case "checkStyleAttribute":
                if (!value.contains("Path")) {
                    checkStyle = Boolean.parseBoolean(value);
                    errorListStyleAttribute = new ArrayList<>();
                }
                break;
            case "checkXrefAndNormalLinks":
                if (!value.contains("Path")) {
                    checkXref = Boolean.parseBoolean(value);
                    errorListXref = new ArrayList<>();
                }
                break;
            case "checkThatAllTopicsHaveConceptKeywords":
                if (!value.contains("Path")) {
                    checkThatAllTopicsHaveConceptKeywords = Boolean.parseBoolean(value);
                    errorListConceptKeywords = new ArrayList<>();
                }
                break;
            case "checkThatAllTopicsHaveIndexKeywords":
                if (!value.contains("Path")) {
                    checkThatAllTopicsHaveIndexKeywords = Boolean.parseBoolean(value);
                    errorListIndexKeywords = new ArrayList<>();
                }
                break;
            case "checkForNoUIElementsInHeadings":
                if (!value.contains("Path")) {
                    checkForNoUIElementsInHeadings = Boolean.parseBoolean(value);
                    errorListUiElements = new ArrayList<>();
                }
                break;
            case "whatElementToCheckForStyle":
                tag = value;
                if (tag.charAt(0) == '[') {
                    tag = tag.substring(1, tag.length() - 1);
                    String[] tags = tag.split(",");
                    for (String t : tags) {
                        tagsToCheck.add(t.trim());
                    }
                } else if (tag.equals("all")) {
                    checkEveryTag = true;
                } else {
                    tagsToCheck.add(tag);
                }
                break;
            case "checkForProductNamesWithoutDNTTag":
                if (!value.contains("Path")) {
                    checkForProductNamesWithoutDNTTag = Boolean.parseBoolean(value);
                    errorProductNamesWithoutDNTTag = new ArrayList<>();
                }
                break;
            default:
                // ignore unrecognized keys
                break;
        }
    }
} catch (IOException e) {
    // handle exception
}

相关问题