Hammers Vs. Nails

August 25, 2014 Steve Hawley

While working on our recent port of DotPdf to Java, I added a number of tools to our overall toolset to enable more functional programming in the class IterableHelper, which is available in the ProductAPI jar.

Of course, one of the tools I put in was fold, which has the following signature:


public static <State, T> State fold(Folder<state, T> folder, State initialState, Iterable<T> sequence)



This particular signature lets me do all kinds of interesting folds which I need in my code base. Technically, I don’t need them, but there are circumstances where a fold or a function based on fold is much easier to read and maintain. Recently, I ported a chunk of code that summed the width of all columns in an iterable data structure. In F#, I might write this function to do the job:



let totalWidth cols = cols |> List.fold (fun sum elem -> sum + elem.Width) 0.0



I could write this in Java, but this is what it will look like (without lambda expression, which I am prevented from using in my codebase):



return IterableHelper.fold(new Folder<Double, Column>() {    


public Double fold(Double state, Column t) {        

return t.getWidth() + state;    


}, 0.0, cols);


With lambda expressions (again, I’m prevented from using them), this example would look like this:



return IterableHelper.fold((Double state, Column t) -> t.getWidth() + state, 0.0, cols);



Which is better, but thinking about the audience that might be maintaining this and the amount of boxing and unboxing, I decided to use the idiomatic Java solution:



double sum = 0; for (Column col : cols) { sum += col.getWidth(); } return sum;



Why? Well, because even when you have a very big hammer like fold, it doesn’t mean that it’s appropriate for every situation.


About the Author

Steve Hawley

Steve was with Atalasoft from 2005 until 2015. He was responsible for the architecture and development of DotImage, and one of the masterminds behind Bacon Day. Steve has over 20 years of experience with companies like Bell Communications Research, Adobe Systems, Newfire, Presto Technologies.

Follow on Twitter More Content by Steve Hawley
Previous Article
Document Tree Viewer with Atalasoft, Part Two
Document Tree Viewer with Atalasoft, Part Two

In Part One of this series, I designed an API for a Document Tree Viewer...

Next Article
Document Tree Viewer with Atalasoft, Part One
Document Tree Viewer with Atalasoft, Part One

Two weeks ago, we surveyed our customers to find out what features they...

Try any of our Imaging SDKs free for 30 days with Full Support

Download Now