Avoiding multiple If statements in Java

后端 未结 13 892
北恋
北恋 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:05

    How about mapping the extensions to MIME types, then using a loop? Something like:

    Map suffixMappings = new HashMap();
    suffixMappings.put(".pdf", "application/pdf");
    ...
    
    private String getMimeType(String fileName){
        if (fileName == null) {
            return "";   
        }
        String suffix = fileName.substring(fileName.lastIndexOf('.'));
        // If fileName might not have extension, check for that above!
        String mimeType = suffixMappings.get(suffix); 
        return mimeType == null ? "text/plain" : mimeType;
     } 
    

提交回复
热议问题