Effective Method Naming
30th October 2008
It sounds like a no brainer doesn’t it? I don’t need lessons on how to name methods, I’ve much more important stuff to think about, like actually coding! I know how you feel, I’m guilty of it myself. However I’ve found that the names given to methods in an application do have a profound effect on it’s readability, and ultimately it’s maintainability.
In an effort to keep my method naming standards up to scratch I’ve come up with three rules. They aren’t the be all and end all of method naming and there are exceptions but as general rules they seem to work pretty well.
A method should do what it says it does and nothing else
The aim of this rule is twofold, to avoid confusion and to avoid surprise. Both of those come back to one point, the goal of every lazy developer, think as little as possible. To avoid confusion the method name should be explicit, it should say exactly what it’s method is going to do, not a vague impression. It should also not contain abbreviations unless they’re universally understood; qFetch() is much less obvious than fetchQueueItem()
To avoid surprise the method should not do things that aren’t stated or implied by the method name. This applies even to larger methods that do a lot, you don’t need to name the method after every little thing that’s done but name it after the whole process. If you’re pulling together lots of smaller methods don’t just name the method doStuff(), give it a name that describes the reason they’ve been pulled together. If you can’t think of one, maybe they should be pulled together in a different way.
A method name should not be longer than it has to be
This is the flip side of the previous rule. We want the method name to be as clear and explicit as possible but at the same time, we don’t want to be inundated with unmanageably long method names. A method name should describe its function but not define it. I think the old database design couplet describes the relationship quite well. Normalize ‘till it hurts, de-normalize ‘till it works.
Method names should follow an application wide standard
This is a rule I’ve seen broken a lot. Never by myself though, because my convention is the clearest, the most universally understood and of course, the most bestest. Yes, conventions are always a tricky (religious) area but they are important. It’s not important whether you fetch stuff from the database or retrieve it, so long as you do the same everywhere. And when I say everywhere I don’t just mean throughout this class, or package, or component, I mean throughout the entire application.
I’ve found these three rules really helpful when naming methods, especially those exposed in external interfaces. Before you make any changes though, remember Martin Fowler’s work on refactoring.

2 comments so far