Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding multiple If statements in Java

Tags:

java

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?

private String getMimeType(String fileName){
  if(fileName == null) {
    return "";   
  } 
  if(fileName.endsWith(".pdf")) {
    return "application/pdf";   
  }
  if(fileName.endsWith(".doc")) {
    return "application/msword";  
  }
  if(fileName.endsWith(".xls")) {
    return "application/vnd.ms-excel"; 
  }
  if(fileName.endsWith(".xlw")) {
    return "application/vnd.ms-excel"; 
  }
  if(fileName.endsWith(".ppt")) {
    return "application/vnd.ms-powerpoint"; 
  }
  if(fileName.endsWith(".mdb")) {
    return "application/x-msaccess"; 
  }
  if(fileName.endsWith(".rtf")) {
    return "application/rtf"; 
  }
  if(fileName.endsWith(".txt")) {
    return "txt/plain"; 
  }
  if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
    return "txt/html"; 
  }
  return "txt/plain"; 
}

I cannot use switch-case here as my 'condition' is a java.lang.String.

like image 652
jai Avatar asked Aug 19 '09 09:08

jai


People also ask

How do you handle multiple if statements in Java?

When using multiple conditions, we use the logical AND && and logical OR || operators. Note: Logical AND && returns true if both statements are true. Logical OR || returns true if any one of the statements is true.


1 Answers

You can use a Map to hold your solutions:

Map<String,String> extensionToMimeType = new HashMap<String,String>();
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";
like image 139
Joachim Sauer Avatar answered Sep 24 '22 06:09

Joachim Sauer