Avoiding multiple If statements in Java

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

    Just to mention it: A direct equivalent to your code would not be using a map for direct lookup (since that would require each extension to have exactly 3 characters) but a for loop:

    ...
    Map extmap = GetExtensionMap();
    for (Map.Entry entry: extmap.entrySet())
      if (fileName.endsWith(entry.getKey))
        return entry.getValue();
    ...
    

    This solution works with extensions of any length but is less performant than the hash lookup of course (and slightly less performant than the original solution)

    The Algorithmic-Design-Guy solution

    A more performant way would be to implement a tree structure starting with the last character of the extension and storing the appropriate MIME types at the respective nodes. You could then walk down the tree starting with the last character of the file name. But this is probably an overkill ...

提交回复
热议问题