15 March 2017

Using Java 8's Function to refactor Decorator and Adapter patterns


Two days into using Java 8 (I know, long overdue, but you know... App Engine), I'm having fun refactoring some legacy (Swing, ouch) codebase.

One of the most powerful new tools is "Function", and I'm discovering how you can refactor entire classes, anymous or not, with one line of code, see for example this question:

Is it possible to pass parameters, or access external parameters to an anonymous class? For example:
int myVariable = 1;

myButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // How would one access myVariable here?
    }
});
Here's my proposed solution, using Function:
Function<Integer,ActionListener> printInt = 
    intvar -> ae -> System.out.println(intvar);

int myVariable = 1;
myButton.addActionListener( printInt.apply(myVariable) );

I think the power of Function becomes obvious when we apply it to refactoring patters such as Decorator, Adapter or other type of proxies.
Here's some code I've just refactored, showing how you can refactor an entire class with a one liner Function:



PS Don't miss this talk by Trisha Gee

No comments:

Post a Comment

Note: only a member of this blog may post a comment.