Avoiding multiple If statements in Java

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

    You can use a Map to hold your solutions:

    Map extensionToMimeType = new HashMap();
    extensionToMimeType.put("pdf", "application/pdf");
    extensionToMimeType.put("doc", "application/msword");
    // and the rest
    
    int lastDot = fileName.lastIndexOf(".");
    String mimeType;
    if (lastDot == -1) {
        mimeType = NO_EXTENSION_MIME_TYPE;
    } else {
        String extension = fileName.substring(lastDot+1);
        mimeType = extensionToMimeType.getOrDefault(extension, 
                                                    UNKNOWN_EXTENSION_MIME_TYPE);
    }
    

    For this code to work you'll need to have defined NO_EXTENSION_MIME_TYPE and UNKNOWN_EXTENSION_MIME_TYPE as in your class, somewhat like this:

    private static final String NO_EXTENSION_MIME_TYPE = "application/octet-stream";
    private static final String UNKNOWN_EXTENSION_MIME_TYPE = "text/plain";
    

提交回复
热议问题