30 June 2017

Short and to the point

Code should be short, simple, and to the point. This is particularly true of methods on a class. Each method should be as short as possible and it should be obvious what is happening. This is a combination of using the simplest code constructs and naming. A metric you can use is the number of lines of code in the method. I frequently use seven or eight as a limit, but ten can work pretty well too. Sometimes it depends upon the language in use. 

Why is this?

I don't know about you but, I have a very short attention span. I like simple things I can plug into my brain with other simple things to make more complicated things. If I have too many complicated things it becomes difficult to use the pieces. 

How do you get there?

A technique I've used for a very long time is to try to place every statement in its own space. So given a condition, the then clause is a method, the else clause is a method etc. If I have a loop, the loop body is (where possible) a method. If you think about your code in terms of 'If this then that', 'that' must be one simple consequence, and therefore in its own method. A loop should say 'While this then that' and again, 'that must be one simple method.

Naming Things

You've certainly hear by now that naming things is one of the hardest parts of programming (an computer science). When you have lots of little methods, naming things gets harder. Harder only because you have to name more things. If you structure things well however, the names should be pretty obvious. If they are not obvious, this is a smell you should pause to consider. If you can't name the simple thing, maybe it isn't that simple. That probably means you've got something complicated on your hands and maybe you need to consider the Single Responsibility Principle. Or possibly you've just found an overly complicated way to go about what you are doing. Either way, this is a good place to pause and reconsider what you are doing.

Visibility

When I test drive, I only write tests for the public or protected interface of a class. Since I don't use inheritance that often, mostly I'm only testing a public interface. Since my classes are very small, I'm often only testing one or maybe two methods. As a result, all those small methods I mentioned are usually private. This gives you a great deal of flexibility in breaking things down. It also allows you to move and rename things easily while your are looking for maximum understandability.