Avoiding multiple If statements in Java

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

    I consider your approach to be the best overall. This comes after having tested with a number of different approaches myself.

    I see a number of huge benefits in your current approach, namely:

    1. Easily readable and understandable by anyone (in my experience, medium-level programmers often underestimate this and usually prefer going with fancy-patterns which, in the end are not readable at all for the vast majority of programmers who do not know that specific pattern)
    2. All the information is in one single place. As Andreas_D pointed out, hunting around files or classes is not a good option for someone that needs to fix a bug while you are on holiday!
    3. Easily maintainable: I could "F3" (if you are Eclipse-ing) on the method and add a new content type in seconds without any worries of introducing bugs!

    I can suggest a few things anyway:

    1. This method is very general purpose: Why should it be private?! This is a public method of some utility/helper class! Moreover it should be a static method!! You don't need anything from the Object itself to perform your job!
    2. You could use indenting to make things prettier and compact. I know that indenting is some kind of religion for the most of us, but I think it should not be a strict rule; it should be properly used to make our code more readable and compact. If this would be a config file you would probably have something like:
    pdf=application/pdf
    doc=application/msword
    

    You could have a very similar result with:

        public static 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"; 
           return "txt/plain"; 
       }
    

    This is also what a lot of the Map based implementations look like.

提交回复
热议问题