2015-03-27

Is Clean Code less Code?

For me clean code is simple, easy to understand code. No over-engineering, as little boilerplate as possible and of course non-cryptic. But does that lead to less code?

I really don’t think so. Most of the times less code is more cryptic and harder to understand (and therefore harder to maintain).

When working with jBehave and testing the meta filtering, I wrote something similar to the following code:

@Override
public Embedder configuredEmbedder() {
Embedder embedder = super.configuredEmbedder();
ignoreStoriesAndScenariosWithMetaInformationParameter(embedder, "ignore");
return embedder;
}

private void ignoreStoriesAndScenariosWithMetaInformationParameter(Embedder embedder, String ignoreParameter) {
embedder.useMetaFilters(Arrays.asList("-" + ignoreParameter));
}

Later, I had a discussion about that code and a colleague said he just deleted the “unnecessary” private method which leads to the following code:

@Override
public Embedder configuredEmbedder() {
Embedder embedder = super.configuredEmbedder();
embedder.useMetaFilters(Arrays.asList("-ignore"));
return embedder;
}

Obviously shorter and less methods. For us, working on that specific class, it may be obvious what’s happening in this method, but just imagine somebody joining the project and never working with jBehave before. For him the longer code provides additional information and even if he does not understand how it works and what “meta filters” are and what the minus means, he’ll at least understand what we are trying to achieve.

When I try to explain my choice, other developers agreed to my point but said that we can also achieve the same result with a comment. And yes, I totally agree that this is a valid option. I think this is just a question of style. I personally don’t like comments (and Uncle Bob’s “Clean Code” is on my site), but maybe in this case the comment really is the better choice because you can explain the connection between this meta filter code and the jBehave story files.

So the resulting code is the following:

@Override
public Embedder configuredEmbedder() {
Embedder embedder = super.configuredEmbedder();
// ignore stories and scenarios with meta information parameter @ignore.
embedder.useMetaFilters(Arrays.asList("-ignore"));
return embedder;
}

Of course you can argue, that this small example isn’t worth talking about. But I think within a project style it is important. And you can find a common style by discussing specific examples. Maybe the other developer will think about if his code could may be unclear to project joiners and I will think about a comment instead of one-line methods.

Conclusion

So clean code isn’t always less code. You need to trade off the benefits of more small methods against lesser lines of code. I’ll discuss the other examples about coding style in some future blog posts.

Which solution is your favorit one and why?