Wednesday, June 24, 2015

Mommy's code can't hold its own pants up

In order to disappoint the reader already before reading this post, this is nothing new. Martin Fowler wrote about this a long time ago in his blog post on the Anemic Domain Model.

This code is about the frustration I sometimes have coming across code that's written in a way that you need to understand the internals first, before you can use it. In other words: the API is not very safe. Let me try to explain.

So - we're going on a family trip - we get everyone in the car and let's go:

But what happens:

Really ?! So apparently we had to set something on MommysBoy - but that wasn't clear at all. Aren't constructor arguments for this?
So how do we solve this ? Let's NOT educate the kid, that will make things more convenient ( NOT ):

He's learnt nothing thusfar. (NOTE: I see this a lot) What I've also seen is writing a service to validate the son. Brilliant - let's get mom in there too, because her son can't go anywhere without her:

*Sigh*... But as a disclaimer - I probably did this too ( and maybe still do ).

There's such a thing as object oriented programming where you just write procedural code and then throw it into classes and methods just to stay DRY, but there's this other world of elegant object-oriented modelling of problems.

So how would I suggest to improve this? Make you're objects just smart enough to take care of themselves, but as dumb as possible. Like in real life :). And think about this: do you allow your object to be in an invalid state ? ( All of this I learnt from ).

You want your son to always have toy? Put it in the constructor. Or pass in a factory ( although he would probably get really spoiled ... ). He's got an age property that should not be negative? Make the setter private - make a SetAge method that checks for a correct value. 

There are so many smells of this type of coding: huge documentation explaining what to take into consideration when running, everything implements IValidateable, constant runtime errors when writing new things and so on.

Just make sure your kids can take care of themselves and save yourself and team a lot of agony!

No comments:

Post a Comment