如何用更好的解决方案替换 switch 语句 - 干净的代码提示 [英] How to substitute switch statement with better solution - clean code hints

查看:27
本文介绍了如何用更好的解决方案替换 switch 语句 - 干净的代码提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

有什么更好更优雅的方法来做到这一点?我不想使用 if,但可能有一些多态性?你能给我一些提示吗?

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?

推荐答案

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

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

这允许您将新支持的类型添加到 Hashtable 中,而不必处理一长串 if/else if/else.

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

这篇关于如何用更好的解决方案替换 switch 语句 - 干净的代码提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆