Tuesday, January 25, 2011

The lazy pattern

"A little bit won't hurt. A little bit doesn't matter." I hear this more than I want and so I'm having to write this little rant to cool me off.

Writing code that works is relatively easy. Writing code that is too complicated is easy too. The balance between easy and over complicated is hard to find. Writing good, SOLID, object-oriented code is the goal.

Every shortcut you do shows to others in your team that it is okay to use shortcuts as well. When a developer is asked to extend a class or add a feature they often just copy what they see around them. And if that is a bunch of little shortcuts it can rapidly become a big problem. 

I rarely see Developers want to improve the camp ground. (Uncle Bob asks us to follow the boy scout rule and leave the camp ground just a little cleaner than it was before.) It's hard work, but I love this rule. I follow it happily.

Take the sink in a student house; if someone leaves a dirty bowl in the sink, the next person comes a long and thinks it's okay to stack their dirty bowl next to the one already there. Before long there are lots and lots of dirty dishes in the sink and it's a big job to clean it all up.

Taking the dirty dishes analogy a little further.

If you are the sort of person that wants to wash their dirty dishes but finds that the sink has dirty items blocking your way, all of a sudden it's a bigger job than you first thought - do you clean all the dishes or do you copy what the other guy did?

This decision point is where that devil laziness really comes into play. Do you do a little bit of lazy code, next to the other little bit of lazy code, after all it isn't really that big a deal.

And so it goes on, a little bit here, a little bit there, and before long everyone is copying the lazy pattern.

I find String to be one of those little lazy decisions that is easy to make, easy to follow and very easy to stack up and get out of control.

For example, the use of String for what really should be a value object, an object that has no conceptual identity. I would extend this to many Strings  like a person's name, a telephone number or a postal code - even if these objects do nothing more than wrap String.

Some would, I'm sure, argue this is over engineering. But if I've got a constructor that takes three parameters, all of them Strings, creating value objects gives you at least some type safety, and an object that can be extended with more behaviour down the line.  Some would say that's just good OO, without it, it's just a bunch of Strings.

I'm not innocent here - I've cut the corners in the past.  But what I have learnt over the last couple of years is to always put that extra effort in, create something that is built around good objects and follow the boy scout rule. It really does pay off and the alternative always bites you in the end.

0 comments:

Post a Comment