如何用更好的解决方案替代switch语句-干净的代码提示 [英] How to substitute switch statement with better solution - clean code hints
问题描述
我创建了一个代码,该代码必须将 ContentDataType
转换为 MIME
类型.例如- ContentDataType
是一个简单的 String
,例如 ImageJPEG
,现在我使用 MediaType.IMAGE_JPEG_VALUE
将其转换为 image/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");
}
}
这使您可以将新的受支持类型添加到哈希表中,而无需处理很长的 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屋!