DaedTech

Stories about Software

By

How to Get Coding Standards Right (and Wrong)

Editorial Note: I originally wrote this post for the NDepend blog.  You can check out the original here, at their site.  While you’re there, download NDepend and give it a try!

Nothing compares with the first week on a new job or team.  You experience an interesting swirl of anticipation, excitement, novelty, nervousness, and probably various other emotions I’m forgetting.  What will your new life be like?  How can you impress your teammates?  Where do you get a cup of coffee around here?

If you write code for a living, you know some specific new job peculiarities.  Do they have a machine with runnable code ready on day one?  Or do you have to go through some protracted onboarding process before you can even look at code?  And speaking of code, does theirs square with elegant use of design patterns and unit testing that they advertised during the interview process?  Or does it look like someone made a Death Star out of bailing wire and glue?

But one of the most pivotal moments (for me, anyway) comes innocuously enough.  It usually happens with an offhand comment from a senior developer or through something mentioned in your orientation packet.  You find yourself directed to the coding standards document.  Oh, boy.

At this point, I start to wonder.  Will I find myself glancing at a one-pager that says, “follow the Microsoft guidelines whenever possible and only include one class per file?”  Or, will I find something far more sinister?  Images of a power-mad architect with a gleam in his eye and a convoluted variable name encoding scheme in his back pocket pop into my head.  Will I therefore spend the next six months waging pitched battles over the placement of underscores?

Ugh, Coding Standards

In this post, believe it or not, I’m going to make the case for coding standards.  But before I do so, I want to make my skepticism very clear.  Accordingly, I want to talk first about how coding standards fail.

Based on personal battle scars and my own experience, I tend to judge coding standard documents as guilty until proven innocent.  I cannot tell you how many groups I have encountered where a coding standard was drafted, “just because.”  In fact, I’ve even written about this in the past.

The Morale Trap

Probably the most obvious failure scenario that I see is the “coding standards as cudgel” one.  In this situation, a strong personality or an “in-crowd” within the team uses the standards documents to bash everyone else into submission.  The standard becomes not a means to any end, but an end unto itself.

When this happens, it can have a brutal effect on the team’s productivity.  Friction and contentiousness mount.  Morale for members of the team tanks.  People feel that their jobs are overly-regimented and lack any need for creativity, leading to behaviors associated with learned helplessness.  No amount of code readability can make up for this.

The Cargo Cult Trap

Part and parcel with learned helplessness becomes what I think of as “the cargo cult trap.”  With an overzealously created, massive standards document, the team comes to worship at the altar of process.  The standards document provides the illusion of guidance in all situations, and gives the team an inappropriate sense of air cover.

Oh, there’s a bug in my code, huh?  Well, that’s unfortunate, but I did follow the standard, so I guess there was really no avoiding it.

Obviously (hopefully), nobody would be quite that obtuse, but you get the idea.  When you have prescriptive guidelines for every conceivable scenario, successfully following all of those guidelines becomes the team’s main charter and challenge.  This holds doubly true if the response to every bug is to mark up the standards document so it never happens again.

The Busywork Trap

The final, and perhaps least insidious, trap that I’ll mention is the busywork trap.  Unlike the morale problems and outsized trust in the standards, this trap offers minimal outright damage.  Instead, you have simple waste.  This also probably occurs most commonly.

In this scenario, the coding standard is created and maintained, but ignored.  Or perhaps the team does not entirely ignore it, but only selectively applies it or else only some of the team pays attention.  Another, similar, situation occurs when the team lays out standards and guidance for rare or nonexistent situations.

I mention this trap because I’ve found it to be the most common.  The team makes a good faith effort at standardizing, only to have that work largely go to waste.

So Where Does It Work?  Where It Solves a Problem.

True to my word, I’ve certainly hammered on the “guilty until proven innocent” theme.  I do this because I believe that prescriptive instruction (like coding standards) should happen not by default, but only to address a gap or shortcoming.

Has the team consistently introduced bugs and wasted troubleshooting time because half of the team uses an underscore prefix to mean one thing, and half another?  Do newer members of the team consistently make a correctness or performance mistake in the code?  Have folks consistently introduced dependencies between projects that create deployment problems?

If you have situations like these, then standardizing helps.  Let a standard evolve out of need; you shouldn’t adopt one as a preventative measure.

Build a System

And that brings me to my final point here.  I’d also argue that this may serve as the differentiator between my thoughts and those of others writing on the topic.  If you must have coding standards, you need to automate them as much as possible.  Automating them provides so many wins and inoculates against some of the traps.

A colleague once told me that it’s best to break bad news by building a system and blaming things on the system.  As a consultant, this has proved immensely valuable to me, and it applies well in the domain of coding standards.

Coding Standards in Code, Not Word

If you really can’t stand camel case or brackets on new lines or whatever, don’t send nasty emails or get into arguments during code review.  And don’t keep the standard in a Word document.  Instead, add something to your build that fails or prevents checkins of code that fails to comply.  Then it’s no one on the team holding judgment, but the tool.

This avoids contentiousness and it allows for a tight feedback loop.  The team learns, and adopts new norms quickly.  It also tends to put to bed (to some extent) religious wars about the standard via a manifestation of squatter’s rights.

What’s more is that automating the standard requires effort, so it tends to put a damper on cargo-cult standard adherence and busywork both.  (Within reason) You’ve really got to want it to go into the build machine and add automation to boot a build back to the committing developer.  That’s harder than sending an email or updating a document.

I mention this on the NDepend blog because I find NDepend to be invaluable in creating systems like this.  It can effortlessly transcend considerations that are both cosmetic, like naming, and design-centric, such as rules about semantics and architecture.  Not to mention that its CQLinq makes the possibilities virtually limitless.

NDepend is, in my opinion, the best tool for the job.  But whatever tool you use, be sure to use a tool.  Coding standards can help you eliminate repeat mistakes and create more maintainable code.  But make sure that the medicine isn’t worse than the disease — make sure you automate.

23 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
DHalonen
DHalonen
7 years ago

A friend is a design engineer for a large domestic automobile manufacturer & I queried him about standards on their blueprints. When asked what would be the impact if designers could put whatever style arrows on dimensions or put the title block in random locations on the print or etc…; his response: “This would shut the company down immediately.”

Programmers are “special”; we don’t abide by rules and we are above the lessons learned by the rest of humanity. Why? We’re special. Get used to it.

Scott Corbett
Scott Corbett
7 years ago
Reply to  DHalonen

This is comparing apples to oranges. The equivalent comparison would be asking what would happen if the people manufacturing the automobile built the parts in a myriad of different ways. My answer is that as long as the designs are being followed, the car will still work to spec. The code a developer builds is equivalent to the parts of the car; the requirements to the blue print, and I know that using the same term to describe two different things in requirements is the cause of all kinds of problems in the same way as designers changing their style.

DHalonen
DHalonen
7 years ago
Reply to  Scott Corbett

My point is that there are communication basics when not observed cause all sorts of problems. Shall we discard all gooder-grammer rules also?

For some reason, developers enjoy a contradiction without appreciating the paradox. Compilers in general, demand, DEMAND I SAY, conformance. For example, a variable cannot start with a digit. We think nothing of this. However, someone states that Hungarian notion is forbidden (or conversely demands it be used), we have a hissy-fit.

As stated earlier, we are “special”.

Erik Dietrich
7 years ago
Reply to  DHalonen

It sounds less like special-ness of programmers and more like a variance in consequences. If a company shut down every time I didn’t follow a variable naming standard, I’d probably automate and thus follow that standard.

goggleboxtech
goggleboxtech
7 years ago

An interesting article.
But I’m sorry, I don’t understand this bit: “it’s best to break by bad news by building a system and blaming things on the system.” I just can’t parse the sentence. Maybe it’s just because I am not American, but is there a typo there? I know the phrase, ‘break bad news’ but it doesn’t seem to help here. You may have to unpack that thought for a dimwit…

Damien
Damien
7 years ago
Reply to  goggleboxtech

Its a toughly worded sentence. Basically he’s advocating building your standards into a system that checks those standards automatically. If its part of actually checking in code, then that’s likely a better bet. A good reason for an automated system checking rather than the team lead or whoever, is that it prevents one member of the team being the “bad guy” and having to take on the role of enforcer. At some point, the enforcer will get busy, bogged down, or simply have some things slip through the cracks. If this is part of checking in code than the added… Read more »

goggleboxtech
goggleboxtech
7 years ago
Reply to  Damien

OK. I get it now. Thank you. 🙂

Paul Taylor
Paul Taylor
7 years ago
Reply to  goggleboxtech

Also, there is indeed a typo. The first ‘by’ should not be there.

Erik Dietrich
7 years ago
Reply to  goggleboxtech

Not your failure to understand — just a typo 🙂

I’ve fixed it now, so hopefully it’s clearer.

AdamTibi
AdamTibi
7 years ago

As a consultant, I know what you mean and I’ve seen this practice in many companies.Today, I believe that stating standards in a Word document is from the ancient eras of software engineering. As you mentioned “Microsoft” I am assuming you are working in .NET, a tool like ReSharper would do that for you and I usually pick the default convention (because it is a convention, there is nothing wrong or right in it) and use it with the rest of the team. No need to maintain or bash team members about conventions as conventions management is centralised within the… Read more »

Erik Dietrich
7 years ago
Reply to  AdamTibi

I’d say R# certainly counts as the kind of automation I like to see, particularly for simple code fixes and linting sorts of stylistic consistency. The reason I favor NDepend as a holistic solution is because I can use its CQLinq to enforce some pretty powerful, custom stuff around code quality concerns if I want.

But I’m totally with you on motivation. I think team members nagging one another about code style these days is an easily solved problem.

KS
KS
7 years ago

I have been through so many coding standard documents and can say that there is no one-size fits all standard. Instead, the solution is for IDEs to apply formatting to individual tastes. If Fred wants leading underscores for private variables- he can see them. For me, leading underscores are invisible and thus useless – so IDE can remove them from display. Indentation and white space are readability issues for most languages. But what is easy to read for one programmer is difficult for another. Again, let the IDE display the code tailored to the individual. There are disadvantages to this… Read more »

Erik Dietrich
7 years ago
Reply to  KS

I like the concept a lot, myself, and totally agree with you. I’ve never understood why those sorts of transforms couldn’t just be applied to suit individual taste. I like the underscores, but I realize that’s just a personal, subjective preference I’ve grown used to. I have no interest in _arguing_ with you or anyone else about that or trying to persuade — I just think we should each be able to see what we’re comfortable with. Years ago, I wrote CodeRush plugin customizations that did exactly that. They converted the team’s standards to my preference and then converted it… Read more »

LarryN
LarryN
7 years ago

Of course the blog’s idea doesn’t solve coding standards disagreements except by crowning one with the winner’s trophy of automation! Automation is is the lobotomizing of the issue, by the one who controls the automattion choice(s)!

Erik Dietrich
7 years ago
Reply to  LarryN

“Lobotomizing of the issue” is an interesting turn of phrase. It makes it sound as though what you prefer instead would be that people spend more time arguing over each check in. But I’m assuming that’s probably not where you’re going. What do you propose instead instead of automation?

I ask because I don’t see how you can ever turn coding standards into something other than arbitrary enshrinement of one person’s preferred style. If you automate, you at least get their faster and with less discord.

LarryN
LarryN
7 years ago
Reply to  Erik Dietrich

Thanks ErikD using init caps. 😉 Think of a group working together, who, as a group, have gone through things as scientists (might often) do — attempting to reach an expanding consensus on the consequences of options. The cohesiveness factor, by which individuals interface on more substantive issues would get a boost, big-time. If I get the respect of the alpha nerd that there is reason X for brace-placement Y, the alpha nerd might bring up an option for my architecture research, pattern research, or other more important issue. Building the human factor, using give-and-take on the braces issue, applies… Read more »

blackbox2
blackbox2
7 years ago

Sigh. I am suffering under just such a power-crazed architect as you describe right now. I’m fine with static analysis for bugs, and with sensible agreements like using C# naming standards, and tabs or spaces (don’t care which as long as everyone does the same). But we’ve got not one but 2 well known code-checking programs carping, nagging and scolding about coding style and readability at every check-in. Far from making code more readable, they actually make it LESS readable, by making fewer lines visible on the screen at the same time, forcing empty lines for no reason apart from… Read more »

Erik Dietrich
7 years ago
Reply to  blackbox2

That sounds like a terrible situation. And, for the record, I wouldn’t blame you for playing games with the gatekeeper. Knowledge workers are smart people, so if bureaucracy prevents them from solving the organization’s real problems, they’ll find their own to solve to amuse themselves.

kentboogaart
kentboogaart
7 years ago

I agree with the sentiment. However, I’m of the position that tooling in .NET is not up to task.

To me, this tooling needs to run as part of the build, whether locally or on the CI server. It needs to cover all used languages (e.g. C# and XAML). And it needs to have a single point of customization (so history of changes can be easily examined/blamed). Finally, it should be capable of automatically correcting those issues that it can.

Unless I’m very much mistaken, we’re a long way from this utopia.

Erik Dietrich
7 years ago
Reply to  kentboogaart

There are tools that will do all of that… sorta. So, I take your point.

In other words, maybe they do all of it, but not for quite so many languages (e.g. XAML) or maybe they do a lot of languages, but don’t have an auto-correction or something. It definitely feels like you’d have to do a lot of mixing and matching to get at this, which defeats the single point of customization.

You mention .NET — is it your experience that there is an ecosystem with a more complete solution compared to .NET?

Andy Bailey
Andy Bailey
7 years ago

Almost every single software project I have been involved in has had some steely-eyed OCD sufferer just waiting to bind us all into their special brand of darkness called “Coding Standards”. I have learned to deal with this quite simply by getting the team to accept the “Java Coding Standard with line length exception” and show them how to turn on the “format on save” feature in NetBeans. This makes the tool responsible for maintaining the coding standard, everyone except the steely-eyed person is happy and we can all get on with being productive instead of anally retentive.

Erik Dietrich
7 years ago
Reply to  Andy Bailey

That sounds like the perfect implementation of what I’m trying to describe here. You agree to something that prevents weird code silos, automate it, and call it a day.

Andy Bailey
Andy Bailey
7 years ago
Reply to  Erik Dietrich

The most important thing is to achieve consensus as quickly as possible and not get bogged down in details. The advantage of using an established standard means not having to invent one and a lot of IDE’s, at least in the Java world, supporting “format on save” means no complicated set up. That is a really easy sell to most developers.