【问题标题】:How to substitute switch statement with better solution - clean code hints如何用更好的解决方案替换 switch 语句 - 干净的代码提示
【发布时间】:2017-06-01 04:09:15
【问题描述】:

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

 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,但也许有一些多态性?你能给我一些提示吗?

【问题讨论】:

  • 也许可以创建一个地图
  • 具有更多代码但可能提供更灵活/动态解决方案的东西是从interface 开始,它可以采用ContentDataType 并返回String,然后你会创建一个注册表,它将通过ContentDataType 映射interface,因此您只需将ContentDataType 传递给注册表,然后根据注册转换器的可用性将String 或null 传回.. . 作为一个想法
  • 但地图需要用值填充。所以我需要做类似put(ContentDataType, MediaType.Extenstion) 的事情。我说的对吗?

标签: java coding-style switch-statement refactoring


【解决方案1】:

这种类型的操作应该使用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;
    }
}

【讨论】:

    【解决方案2】:

    如果你准备好只使用一个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");
        }
    }
    

    这允许您将新的受支持类型添加到 Hashtable 中,而无需处理长序列 if/else if/else。

    【讨论】:

    • 1) 不要使用HashTable 使用HashMap,除非你确实需要同步; 2)get并检查null,而不是使用containsKey和get(只做一次查找更便宜,前者可以是原子的,后者不能直接)
    • 另外,在异常消息中打印有问题的contentDataType 会很有用。
    • 我希望这是最好的选择。谢谢您的回答。我只把Hashtable改成了HashMap
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2021-04-20
    • 2012-04-06
    相关资源
    最近更新 更多