Avoiding multiple If statements in Java

后端 未结 13 855
北恋
北恋 2020-12-30 07:52

I\'ve coded a method something like this. But I guess this should undergo refactoring. Can any one suggest the best approach to avoid using this multiple if statements?

13条回答
  •  情话喂你
    2020-12-30 08:13

    Personally I don't have problems with the if statements. The code is readable, it took just milliseconds to understand what you're doing. It's a private method anyway and if the list of mime types is static then there's no urgent need to move the mapping to a properties file and use a lookup table (map). Map would reduce lines of code, but to understand the code, then you're forced to read the code and the implementation of the mapping - either a static initializer or an external file.

    You could change the code a bit and use an enum:

    private enum FileExtension { NONE, DEFAULT, PDF, DOC, XLS /* ... */ }
    
    private String getMimeType(String fileName){
      String mimeType = null;
    
      FileExtension fileNameExtension = getFileNameExtension(fileName);
    
      switch(fileNameExtension) {
        case NONE:
          return "";
        case PDF:
          return "application/pdf";
    
        // ...
    
        case DEFAULT:
          return "txt/plain";   
      }
    
      throw new RuntimeException("Unhandled FileExtension detected");
    } 
    

    The getFileNameExtension(String fileName) method will just return the fitting enum value for the fileName, FileExtension.NONE if fileName is empty (or null?) and FileExtension.DEFAULT if the file extension is not mapped to a mime type.

提交回复
热议问题