如何用更好的解决方案替换 switch 语句 - 干净的代码提示

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

我创建了一个代码,它必须将 ContentDataType 转换为 MIME 类型。例如 - ContentDataType 是一个简单的 String,就像 ImageJPEG,现在我使用 MediaType.IMAGE_JPEG_VALUE 将其转换为 image/jpeg。但我使用开关来做到这一点。这是一个代码:

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

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

执行此操作的更好、更优雅的方法是什么?我不想使用 if,但也许有些多态性?你能给我一些提示吗?

如果您准备只使用一个 if/else您可以这样做:

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");
    }
}

这允许您将新的受支持类型添加到哈希表中,而不必处理 if/else if/else.

的长序列

这种操作应该使用Enum。

如果您的 ContentDataType 具有所有已知的可能选项,则为其创建一个枚举。

然后你可以存储字符串以及MIME类型。如下所示,

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;
    }
}

或者您可以使用 MimeType 对象以及下面的方法

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;
    }
}