如果条件是具有不同参数的方法,如何替换 multi if/else 语句

How to replace multi if/else statement if condition is a method with different params

我找到了条件是相同字段的答案,例如if a==1 if a==2 等我可以轻松将其更改为 switch,但是在下面的情况下呢?

但是如果条件是一个方法呢(方法相同,区别仅在一个参数)

这是一个例子:

public float doSomething(Object object) throws invalidObjectException {
    float numberToReturn = 0f;

    if (isTypeValid(messages.getString("param1"), object.getType())) {
        //do something e.g.
        numberToReturn += Integer.parseInt(object.getTime()) * 1;
    } else if (isTypeValid(messages.getString("param2"), object.getType())) {
        //do something else e.g.
        numberToReturn += Float.parseFloat(object.getTime()) * 2;
    } else if (isTypeValid(messages.getString("param3"), object.getType())) {
        //do something else e.g.
        numberToReturn += Integer.parseInt(object.getTime()) * 3;

    } else {
        //do something else e.g.
        throw new invalidObjectException("Type " + object.getType() + " is invalid.");
    }
    return numberToReturn;
}

你可以注意到我有几乎相同的 if 条件(区别在于第一个参数)和

有什么想法可以使它对其他程序员更具可读性吗?

我认为这不是很重要,但这就是我的 isTpeValid 的样子。

public boolean isTypeValid(String validTypes, String actualType) {
    String[] split = validTypes.split("\s+");
    return Arrays.asList(split).contains(actualType) ? true : false;
}

messages.getString("param2") 是 i18n(国际化)的一部分,我们有

ResourceBundle messages = ResourceBundle.getBundle("file_name", locale);

在 file_name_en 中,我有具有有效英语类型的示例数据:

param1=a b c
param2=d e
param3=f

在 file_name_de 中,我有有效类型的德语示例数据:

param1=g h
param2=i j k 
param3=l

举个例子上面说:

if object.getType is valid with param1:
    //do something
if object.getType is valid with param2:
    //do something else etc.

您可以在 repl.it

上找到以下代码的工作示例

代码

您可以通过创建使用类型作为键和函数作为值的查找 table 来替换 if-else

Map<String, BiFunction<String, Float, Float>> typeFunctionLookup = new HashMap<>();
typeFunctionLookup.put("a", (time, x) -> x + Integer.parseInt(time) * 1);
typeFunctionLookup.put("b", (time, x) -> x + Float.parseFloat(time) * 2);
typeFunctionLookup.put("c", (time, x) -> x + Integer.parseInt(time) * 3);

之后我们必须在此查找值中找到一个类型。这可以通过以下方式完成:

public static Optional<Entry<String, BiFunction<String, Float, Float>>> findEntry(String type, Map<String, BiFunction<String, Float, Float>> types) {
    return types.entrySet().stream()
          .filter(x -> isTypeValid(x.getKey(), type))
          .findFirst();
}

findEntry return 一个 Optional。如果存在这个选项,我们要执行地图存储的功能。否则我们将只 return 值而不用函数改变它。

public static float handeType(Optional<Entry<String, BiFunction<String, Float, Float>>> type, String time, float value) {
    return type.isPresent() 
        ? type.get().getValue().apply(time, value)
        : value;
}

现在我们可以调用 handeType(findEntry(TYPE, typeFunctionLookup), OBJECT_TIME, OBJECT_TYPE)