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/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 语句 - 干净的代码提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何用更好的解决方案替换 switch 语句 - 干净的代码提示
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
