Monday, 5 December 2011

Functional Programming... Ner, don't bother....

I've just had one of those moments, where I feel like the only programmer in the room who knows what they're on with... let me walk you through this one...

You have a complex piece of code, to sum the number of some values from a series of records where the record type is some given subtype... for example, you have a database of cars, you want to sum all the red cars registered in the last year... you want to sum the green cars... and then you want to sum the blue cars... Generically speaking, you can see where this is going, I'm sure:

function SumCars (Colour Col)
{
return   ( SELECT * FROM Cars WHERE Colour = Col );
}

function SumRedCars ()
{
return SumCars ('Red');
}

function SumGreenCars ()
{
return SumCars ('Green');
}

and so on... this seems very simple yes... and you gain a single function, which is referenced by other sub-functions... now imagine that the "SumCars" function is very very complex (lets say, 350 lines of code) with different if-else and switch statements controlling different pathways through it.

Now, think about what the above style of code does for you, it makes a single copy of that huge function, and you just call that wherever you want... Great eh?... This is one of the tennants of good coding and functional programming.  In my book its one of the best parts of programming.

This makes the code more maintainable, easier to read, and more approachable.  I certainly don't do this kind of coding just to say "mine is better".  If there is a better way to do this sort of thing please show me.  No, what has gotten me utterly buffuddled today is the approach of a collegue of mine, whom has not grasped the situation above at all, and indeed has labelled my approach (what many of you I'm sure would consider the standard approach) to be obfuscating the purpose of the code at hand...

Now, I let them goad me, and I'm utterly lost, here's their solution...

function SumRedCars ()
{
REALLY
LONG COMPLEX CODE
WITH Red INSIDE
}

function SumRedCars ()
{
REALLY
LONG COMPLEX CODE
WITH Blue INSIDE
}

Yes, they want to copy and paste the really complex part and have a copy for every instance or parameter they want to pass in... and they see nothing wrong with this... they see this as being the correct way to work...

And it makes me want to chew my arm off just to have something to throw at them.

No comments:

Post a Comment