Tuesday, August 5, 2008

What's in your object?

In the ThoughtWorks Anthology, there's an essay by Jeff Bay called Object Calisthenics. Briefly, the essay lays out a set of rules for designing classes that are rather strict and quite different from what you'd normally use to guide your programming. If you do a quick Google, you'll see that this essay has received quite a bit of criticism in the blogosphere. Most people seem to say that the rules are too strict and just get in the way.

If you haven't read the essay, there's an overview here.

I'm applying these rules as much as I can in my day to day development, and I've noticed a few things. First, it's not kind toward legacy code bases. It is especially unkind toward WPF applications. WPF is built almost entirely on .NET properties and practically begs you to break encapsulation. Yuck... but I blame WPF rather than these rules.

Next, it's turned my code inside out. I'm used to grabbing a few objects, getting some data out of them, doing something to that data, and then passing that data to some other method. Usually this is so I can then return a new value. Since I'm not doing gets anymore, I have to send commands to those objects and then let them do some computation on behalf of the caller. It kinda reminds me of the message passing style you do in Erlang.

So what's this gotten me? For one, unit testing is easier. If you use get, you end up with an object that you then have to verify. This object will have state of its own which will likely have to be verified. This isn't a unit test anymore. It's an integration test. Instead, by sending messages, especially with mocks as parameters, you only have one layer of code to test.

Also, Dependency Injection become much more natural. But that's a topic for another post.

No comments: