How to substitute switch statement with better solution - clean code hints

偶尔善良 提交于 2020-01-30 06:43:06

问题


I created a code, which have to convert ContentDataType into MIME types. For example - ContentDataType is a simple String like ImageJPEG and now I use MediaType.IMAGE_JPEG_VALUE to convert it into image/jpeg. But I use switch to do this. This is a code:

 public static String createContentType(ContentDataType contentDataType) {
        String contentType;

        switch (contentDataType) {          
            case IMAGE_JPG:
                contentType = MediaType.IMAGE_JPEG_VALUE;
                break;
            //next media types
        }
    return contentType;
 }

What is a better and elegant way to do this? I do not want to use if, but maybe some polymorphism? Can you give me any hints?


回答1:


If you are ready to use just one if/elseYou can do something like this :

private static Hashtable<String, String> types = new Hashtable<>();

static{
    types.put(IMAGE_JPG, MediaType.IMAGE_JPEG_VALUE);
    types.put(IMAGE_PNG, MediaType.IMAGE_PNG_VALUE);
    types.put(IMAGE_XXX, MediaType.IMAGE_XXX_VALUE);
}

public static String createContentType(ContentDataType contentDataType) {
    if types.containsKey(contentDataType) 
        return types.get(contentDataType);
    else
        throw new RuntimeException("contentDataType not supported");
    }
}

This allows you to add new supported types into the Hashtable whitout having to deal with a long sequence of if/else if/else.




回答2:


This type of operation should be used Enum.

If you have all the known possible options for your ContentDataType, then create a enum for the same.

Then you can store string as well as MIME type. like below,

enum ContentDataType{
    IMAGE_JPG("ImageJPG", "image/jpg"),
    IMAGE_GIF("ImageGIF", "image/gif");
    String contentType;
    String mimeType;
    ContentDataType(String contentType, String mimeType){
        this.contentType = contentType;
        this.mimeType = mimeType;
    }
}

Or you can use MimeType object as well as below

import com.google.common.net.MediaType;
enum ContentDataType{
    IMAGE_JPG("ImageJPG", MediaType.JPEG),
    IMAGE_GIF("ImageGIF", MediaType.GIF);
    public String contentType;
    public MediaType mimeType;
    ContentDataType(String contentType, MediaType mimeType){
        this.contentType = contentType;
        this.mimeType = mimeType;
    }
}


来源:https://stackoverflow.com/questions/41691323/how-to-substitute-switch-statement-with-better-solution-clean-code-hints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!