用Java编写函数?

whe*_*ies 9 java functional-programming dry function-composition

我正在为我们创建的API编写演示代码,并且我一直在遇到同样的问题,我正在重复自己,一遍又一遍地恶心.我很痛苦地意识到Java计划添加闭包但我现在无法访问它们.以下是我想在其自己的小角落里插入的地方重复的内容:

public BarObj Foo(Double..._input){
    try{
        //things that vary per function
        //but everything else...
    } catch(NullException _null){
        m_Logger.error("Null error exception caught in Blah::Foo");

        return null;
    } catch(Exception ex){
        m_Logger.error( ex.getMessage() );

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

关于我认为解决这个问题的唯一方法是将一个Method函数传递给一个函数,该函数带有try-catch逻辑并将其全部包含在另一个函数中,如下所示:

public BarObj MyFunc(Double..._input){
    return compose("MyLogic",_input);
}

private BarObj MyLogic(Double..._input) 
    throws Exception{
    //stuff
}
Run Code Online (Sandbox Code Playgroud)

但它看起来很丑陋并带有很多样板.有没有更简单的方法来编写Java中的函数?

dfa*_*dfa 8

在Java中,这是非常困难的,因为没有对函数的一流支持(不像clojure或scala,可能还有其他).

但是,您可以操作封装在对象中:

interface Function<R, T> {

     R call(T... input);
}
Run Code Online (Sandbox Code Playgroud)

然后重构Foo为:

static <R, T> R runFunction(Function<R, T> function, T ... input){
    try{
       return function.call(input);
    } catch(NullPointerException _null){
       m_Logger.error("Null error exception caught in Blah::Foo");
       return null;
    } catch(Exception ex){
       m_Logger.error( ex.getMessage() );
       return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

测试用例:

class SumDoubles implements Function<Double, Double> {

    @Override
    public Double call(Double... input) {
        Double sum = 0.0;

        for (Double d : input) {
            sum += d;
        }

        return sum;
    }
}

@Test
public void sum() {
    Double sum = runFunction(new SumDoubles(), 1.0, 2.0, 3.0);
    assertThat(sum, is(6.0));
}
Run Code Online (Sandbox Code Playgroud)