Those of you who know me in person will know that the more relevant something is the less likely I am to remember it. Since that only seems to be getting worse lately I want to start recording some of the really simple aha! moments I have so that I don't have to figure them out from scratch all the time. Here's the first.
One thing some of my new colleagues seem really big on is giving things good names. Clearly this is a good thing but it can be pretty challenging if you haven't practiced it rigorously in the past. Over the last few weeks I'd coded a couple of classes I was really uneasy about. These classes ended up with nothing but one or two static methods and a really forced name. Here's a nice contrived example based on sports:
public static class BallThrower
{
public static void Throw()
{
...
}
}
Obviously names have been changed to protect the innocent. The trouble I had with this was that I had decided balls needed to be thrown ended up writing a nice procedural style method to do just that. The class may as well not exist as I have basically written a single static action. Seeing BallThrower.Throw() in the middle of the code doesn't give anyone any clues about what is going on or how it relates to the problem.
After chatting with a few of the people around me I was prompted to ask the question that is the title of this post. More directly the question is:
What object in the problem domain does this action belong to?
When I say problem domain here I simply mean the application as the client might describe it. Instead of fumbling about trying to find new names to hide my dirty little class behind I should have realised that balls don't just get thrown by themselves. Something has to throw a ball and I already have a perfectly good name for something that throws a ball in my domain:
public class Player
{
public void ThrowBall()
{
...
}
}
This seems pretty obvious now so why did it take me so long to get here?
Until this point the need for the Player object hadn't even come up. I had been taking a short sighted approach to objects and creating one wherever I had data to store. Since I didn't have any need to store any player attributes (though it easy to think of many potential ones) the name never occurred to me.
I think I'll record the following as the notes I want to remember:
- If you're not comfortable with what you've written go back through your problem domain and see if there is a more obvious way to express it.
- Objects encapsulate behaviour as well as data.
Labels: Aha, Object Oriented Programming, Style
30/06/2008 04:33 AM (UTC -07:00)