有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在条件是具有不同参数的方法时替换多if/else语句

我找到了条件是相同字段的答案,例如if a==1if 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;
}

留言。getString(“param2”)是i18n(Internationalization)的一部分,我们有

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

在文件_name _en中,我有英文有效类型的示例数据:

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

在文件_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.

共 (1) 个答案

  1. # 1 楼答案

    您可以在repl.it上找到以下代码的工作示例

    密码

    可以通过创建一个查找表来替换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返回一个Optional。如果这个选项存在,我们需要执行映射存储的函数。否则,我们将只返回值,而不通过函数进行更改

    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)