Tuesday, January 20, 2015

Give Up The func

There is a Thing about learning new languages - it tends to make you Think Differently.

I've written a lot of perl and Java over the years & so it took me a while to get the whole Functional Programming thing...

It basically took me learning Swift.

That being said - I don't write Swift code for a living.

As a result there strange new ideas have been seeping out into my perl & Java code.

I recently found myself, for example, emulating functional programming in Java by using an Enum as a return-type which would trigger a variety of different methods with a switch statement.  

Each different element of the Enum is treated as a case inside the switch.  

Then for the last line of the switch I added:
throw new AssertionError(this.name());

Which is essentially the compiler saying "WTF?"...

Admittedly this is, at best, a very weak example of Functional Programming - but I'm not here to demonstrate the Java implementation of a Closure - others have done that far better than I could.

The point of this is that simply that rather than limiting myself to the constraints of managing a return-type - that type itself might reflect a relationship to varied behavior.

Does that mean that we can pass around references to functions?  Not exactly, but usually what you are trying to accomplish can still be done with some code contortionism.

Loose functions are simply methods in Java so an Enum of triggers could fire cases in a switch, all of which behave differently & call various methods.

Depending on what data those methods need to access dictates if they are Class methods or if you need to define a Class to generate object instances.

No comments:

Post a Comment