Wednesday, December 14, 2005

Functional Style

Elizabeth Keogh in her Traversing the Ocean of Knowledge blog, points out how all the evils of programming boil down to unwanted corruption of state. 

Yet, it is possible to program without keeping state.  You can produce a flow of function calls, where the objects just flow through as arguments within the functional streams.   However, the trick works only if your functions are side-effect free, as Eric Evans points out.  If your functions are side effect free they cannot corrupt any shared state and they will always return the same thing when given the same arguments.

I will give a simple practical example.
data_list_A = DataListA.new("..").load()
data_list_B = DataListB.new("..").load()

engine = Engine.new(data_list_A,data_list_B)
engine.setup(...)
result = engine.calculate(..,...,...)
Here we have three pieces of state needed to get the result we want.  If the example were slightly more complex, those states could get corrupted along the way by misbehaving code.  We also have temporal coupling here: those statements must be in the order I have written them.  They are coupled by that sequence and any attempt to change that order is likely to result in a program failure.

On the other hand I could write the same code in more functional style:

result = Engine.new (
             DataListA("..").new.load(),
             DataListB("..").new.load()
         ).calculate(..,...,...)

If you like to try an intentional style, you can wrap up all the nasty syntax into functions and go for the more expressive:

result = Engine( DataListA(".."), DataListB("..") ).calculate(..,...,...)





Comments: Post a Comment

Links to this post:

Create a Link



<< Home

This page is powered by Blogger. Isn't yours?