Ash*_*sha 24 java refactoring if-statement conditional-statements
我有以下代码:
void f(String t)
{
if(t.equals("a"))
{
someObject.setType(ObjectType.TYPE_A);
}
else if(t.equals("b"))
{
someObject.setType(ObjectType.TYPE_B);
}
// 50 more similar code
}
Run Code Online (Sandbox Code Playgroud)
有没有简单的方法来重写if-else条件,以便没有那么多代码?
Mar*_*nik 50
你应该使用一些东西来消除someObject.setType(ObjectType....))
If ObjectType
is a 的重复enum
,然后编写一个类似的方法来valueOf
实现它.看看你是否喜欢这种解决方案:
void f(String t) { someObject.setType(ObjectType.byName(t)); }
enum ObjectType {
TYPE_A, TYPE_B;
public static ObjectType byName(String name) {
return valueOf("TYPE_" + name.toUpperCase());
}
}
Run Code Online (Sandbox Code Playgroud)
JB *_*zet 14
我会将此添加为枚举的功能:
public enum ObjectType {
TYPE_A("a"),
TYPE_B("b");
private String stringType;
private ObjectType(String stringType) {
this.stringType = stringType;
}
public String getStringType() {
return this.stringType;
}
public static ObjectType fromStringType(String s) {
for (ObjectType type : ObjectType.values()) {
if (type.stringType.equals(s)) {
return type;
}
}
throw new IllegalArgumentException("No ObjectType with stringType " + s);
}
}
...
void f(String t) {
someObject.setType(ObjectType.fromStringType(t));
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5248 次 |
最近记录: |