I’m writing demo code for an API we’ve created and I keep running into the same problem where I’m repeating myself, over and over ad nauseum. I am painfully aware that Java is scheduled to have closures added but I don’t have access to them now. Here is what is repeated all over the place that I’d like to just box into it’s own little corner:
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;
}
}
About the only way I’ve thought to go around this is by passing a Method into a function which carries with it the try-catch logic and wrapping it all up in another function like so:
public BarObj MyFunc(Double..._input){
return compose("MyLogic",_input);
}
private BarObj MyLogic(Double..._input)
throws Exception{
//stuff
}
but it looks ugly and carries with it a lot of boilerplate. Is there an easier way to compose functions in Java?
in Java this is very difficult since there is no first class support for functions (unlike clojure or scala and probably other).
However, you can encapsulate the operation in an object:
then refactor
Fooas:testcase: