Monday, February 12th, 2007

A Measure of Style

Can you measure coding style? Yes, it is possible, but don’t expect too simple results. The main complication is that there are plenty of strong opinions about what constitutes good coding style.

If you tell a colleague their coding style could be improved, you likely conjure up a passion you never knew the person possessed. It’s easier to have a dumb program calculate some metrics. All metrics are flawed one way or the other, but at least it’s neutral and everyone is sized up along the same scale.

Metrics is like borrowing somebody else’s eyes. It may help locate quality problems. Bad coding style tends to increase bug reports and support costs.

So what can you measure? One of the simplest metrics is comment density. Too few comments signals that the design perhaps only exists in somebody’s mind. Another simple measurement is cyclomatic complexity. It is calculated on individual methods or functions. A high value means the logic is hard to follow and consequently difficult (i.e. expensive) to modify.

Going to a higher level, metrics have been developed to capture good object-oriented design. Most attempt to quantify dependencies between classes or subsystems. A system with deeply intertwined modules tends to get fragile; it easily breaks when modified. There are variations on this theme: Are internal object states protected from other classes? Does a high-level class depend on details in a low-level class?

If you don’t have a metrics tool, search the web for “metrics” and the name of your programming language. You will almost certainly find a few tools out there with a free evaluation period. The cure for bad metrics is usually refactoring. Refactoring is very difficult to do manually, so many metrics tools also support refactoring.

It may hurt one’s pride to have a program judge one’s coding style, but in my opinion we might as well get used to it.

Comments are closed.