Statically Typed

because Hindley-Milner rocks

Composing Functions: the Java approach vs the Scala approach


I asked a simple question in Stack Overflow and got back the kind of answer I should have expected, a strategy pattern.  For illustrative purposes I’ll repeat the problem here:

public Bar myFoo(Double..._input){
    try{
        //do stuff
    }
    catch(Exception ex){
        m_Logger.error( ex.getMessage() );

        return null;
    }

    return output;
}

constantly repeats in all my functions.  How to get it all into one place without resorting to reflection?  The answer is, of course, to use the Strategy pattern:

interface Function<R,T>{
    public R call(T..._input);
}

will represent the Strategy pattern for each of my previous member function.  A new function with the form

protected <R,T> R actionFoo(Function<R,T> _func, T..._input){
    try{
        return _func.call( _input );
    }
    catch(Exception ex){
        m_Logger.error( ex.getMessage() );

        return null;
    }
}

is placed into my FooClass .  Then when I want to call a function I instantiate a new class for each function, like so

public Bar myFunc1(Double..._input){
    return actionFoo( new DoSomething(), _input );
}

public Bar myFunc2(Double..._input){
    return actionFoo( new DoSomethingElse(), _input );
}

Wait, what!?  At this point I have to ask if I’ve really saved anything at all?  Is my code now smaller or larger?  Is it more readable?  I tried this and not surprisingly the code grew in size while at the same time becoming less expressive.  I now had a new inner class for each public method, a new interface, and a new secondary function to wrap it all.

What does it look like in Scala?

def myFoo(_input: Array[Double]) = {
    def fooAction( _input: Array[Double]) ={
        //stuff to do
    }
    actionFoo fooAction( _input )
}

That’s right.  With only an inner defined function and another function defined somewhere else which does nothing at all but the try-catch clause I’ve got all my functionality in one place.  Has the number of lines of code diminished?  Yes.  Is it more readable?  Yes.  Does it still do all that I want it to do?  Hell yes.

Why, oh why, would I want to chose Java over Scala?  I have no idea.  This is why I like functional programming.  I can get more done in less lines of code and better clarity of intent than I ever could with a strictly imperative language.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Information

This entry was posted on February 8, 2010 by in Java, Scala.
%d bloggers like this: