How to substitute switch statement with better solution - clean code hints(如何用更好的解决方案替换 switch 语句 - 干净的代码提示)
问题描述
我创建了一个代码,它必须将 ContentDataType
转换为 MIME
类型.例如 - ContentDataType
是一个简单的 String
像 ImageJPEG
现在我使用 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/else
You 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 语句 - 干净的代码提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何用更好的解决方案替换 switch 语句 - 干净的代码提示


基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01