Wednesday, September 16, 2015

Functional Java...

Functional Java...  In the bad old days before Java 1.8 (before lambdas, in other words), if you wanted to list the subdirectories of a given directory, you'd write something like this:
files = _node.listFiles( new FilenameFilter() {
    @Override    public boolean accept( final File node, final String name ) {
        return new File( node, name ).isDirectory();
    }
} );
That's an anonymous class declaration, complete with all the mess of Java wordiness that goes along with it.  Ugly, dense, and way too hard to understand.

Today I wrote one like this:
files = _node.listFiles( (node, name) -> { return new File( node, name ).isDirectory(); } );
That's a lambda in there: short, to the point, and easy to read.

I know it's a crazy simple example, and doesn't at all show off the power of lambdas or functional programming.  But anything that replaces the gobbledygook of the first example with the (relative) clarity of the second is a winner in my book.  Me like!

No comments:

Post a Comment