Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

What should be in a good (read:useful) coding standard?

  • Things the code should have.
  • Things the code shouldn't have.
  • Should the coding standard include definitions of things the language, compiler, or code formatter enforces?
  • What about metrics like cyclomatic complexity, lines per file, etc?
share

locked by Yannis Rizos Aug 4 '13 at 13:16

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

closed as not constructive by gnat, Walter, thorsten müller, GlenH7, Thomas Owens Nov 30 '12 at 12:51

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

show 1 more comment

20 Answers 20

up vote 40 down vote accepted

A reasons for every requirement. This way, following the standard doesn't become some sort of cargo cult and people know that it's ok to change the standard if the reason for it no longer applies, or to violate the standard in specific cases where the reason clearly doesn't apply.

share
3  
Absolutely. Every item in a standard should have the rationale specified explicitly. –  AShelly Oct 29 '10 at 19:17
4  
Sometimes there is no good reason for a choice, but it's desirable to have everybody do the same. I don't know why we all drive on the right, to use a car analogy, but it's much better than half on the right and half on the left. –  David Thornley Oct 29 '10 at 20:01
9  
@David: That's a perfectly legitimate reason for having a coding standard. If that's the reason then it should simply be stated as such, i.e. "Reason: To improve consistency of the codebase." –  dsimcha Oct 29 '10 at 20:21
show 1 more comment

Tabs vs Spaces! I get crazy updates when one of my colleagues accidentally commits a lot of tabs to spaces shift into the repository

share
1  
I agree wholeheartedly! –  matiash Oct 29 '10 at 18:44
2  
IMHO, that's an only thing that deserves being in a coding standard. –  Pavel Shved Oct 29 '10 at 19:36
1  
2  
IMHO, that is a excellent example of what a coding standard should not cover. –  Bjarke Freund-Hansen Dec 9 '10 at 15:07
show 3 more comments

Naming Conventions

EDIT: By this I mean naming Guidelines, not naming Rules.

For example, a Guideline would be All boolean values should begin with Is/Can/Has/etc when possible. A rule would be All boolean values must start with Is

share
3  
LPSZ* lppsz_CPP_MrKim_ClassOfStudents[][]; –  muntoo Oct 30 '10 at 1:00
3  
-1: This is exactly the sort of low-level detail that causes developers to ignore standards. You might as well mandate that everyone wear neckties. –  TMN Dec 9 '10 at 14:58
2  
@TMN: Lack of naming conventions are the exact sort of thing that causes developers to despair of ever understanding the code. They don't have to be nit-picky, but a few general guidelines will help immensely. –  David Thornley Dec 9 '10 at 15:32
1  
@Rachel: Yeah, we had the "all boolean properties must start with 'Is'" standard. Wound up with properties like IsCanUpdate and IsHasChildren. Sure, it's wrong, but it was decreed in the standard. And this is my point: once you start specifying these things, you have to make sure you cover all the bases, or else people run into something the standard doesn't cover, or covers badly, and then they either write something that's wrong, or they start ignoring the standard. Either way, the team loses. –  TMN Dec 9 '10 at 19:08
1  
That's why I think it should include Guidelines, not Rules, for how to name your objects. Exact names are still left up to the developers. I'll edit my answer. –  Rachel Dec 10 '10 at 16:25
show 3 more comments

A coding standard for a group should include the compiler options for warnings and errors that must be addressed.

Programmers should be free to increase warnings for their own code, but there must be a baseline so that reading and working with someone else's code doesn't clutter up the output you get from the compiler.

Such a standard would also have to address how programmers can disable such warnings case-by-case, should there be an exceptional piece of code that won't otherwise conform.

share
show 4 more comments

Some standards I like (I know there is a lot of them, but that's those I prefer):

  • 80% unit tests coverage
  • Collective ownership of the code (write code to be read by your team mates, not the compiler)
  • Write comments. Write what you would say to a newcomer.
  • Keep it simple
share
show 8 more comments

Coding Standards help a little when you are writing the code the first time, they help a lot when you, or your replacement, has to update the code 2 years later.

The ideal standard leads to code where you can jump to any arbitrary page in the code, and understand excactly what it is doing on the first read-through, because

  • the names clearly describe what data is being manipulated,
  • the braces make the flow of control clear,
  • the comments explain any non-obvious algorithm, etc.

On the other hand, too many arbitrary standards can disrupt the flow of writing code. So I believe that every item in a proposed coding convention should be evaluated against these 2 criteria:

  • Does this rule help ensure that the code is Correct?
  • Does this rule help ensure that the code is Clear?

If neither is true, the item is just arbitrary, and probably unnecessary


I would include the following things in a standard I write:

For Clarity:

  • File Organization: Specifying a fixed order for the items in a file lets the team easily navigate others files. You shouldn't have to hunt to find #defines, or structure definitions.

  • Naming conventions: Consistent naming aids readability. But avoid over-specifying too many rules, that harms writeability.

  • Code Structure. Curly Brace placement, indentation levels, spaces vs tabs, etc. Yes, this can be a strong personal preference, but the goal is clear code. Find the best option for the team, and stick with it.

For Correctness:

  • Best Practices specific to your problem type: Rules about memory allocation, or concurrency, or portability.

  • "Const Correctnesss", proper use of static and volatile, etc.

  • Rules about preprocessor macros, and other easily abused features of the language.

share
add comment

Inspiring, pragmatic ideas that make people think, rather than negative restrictions which stop people thinking.

Otherwise, you get code monkeys who are afraid to go after the bananas.

share
add comment

What should be in a coding standard? As little as possible. Less rather more. And with justification, please.

Not because I'm some cowboy coder who wants no process, but because I've seen heavy coding specs with no logic behind it beyond (presumably) "I found this on the 'Net somewhere back in '95" that just end up becoming a bureaucratic nightmare to work with.

Some people honestly seem to believe that by cranking up the standards they will see a corresponding increase in code "quality" and perhaps by that measure they will. In the meantime they'll ignore architecture, performance, common sense and a bunch other things that end up mattering more than the number of lines in a file.

share
add comment

A procedure for code reviews to enforce the standard. Oh, and to find bugs too.

share
add comment

Some good old common sense wouldn’t go amiss; there are far too many coding standard documents that labour on irrelevant points (items such as font type and size being one of the more extreme ones I’ve seen).

The best thing to do if you’re in a group of developers is to talk to each other and look at your code, form a consensus on what is acceptable and if you need to write down the main points as guidelines, but keep them as just that guidelines. If you can’t justify any divergence from the guidelines you really should consider why you’re doing it.

At the end of the day clear and understandable code is more important than any rigid rule on layout or typography.

share
show 3 more comments

As others have mentioned, code test coverage is important. I also like to see:

  • Project structure. Are the tests part of the code, or are they in a separate project/package/directory? Does the UI code live with the back-end stuff? If not, how is it compartmentalized?

  • Development process. Write tests before code? Does fixing broken builds take priority over development? When are code reviews done, and what should they cover?

  • Source code management. What gets checked in when? Are design docs and test plans revision-controlled? When do you branch and when do you tag? Do you keep previous builds, and if so how many/for how long?

  • Deployment standards. How is a build packaged? What needs to go into release notes? How are upgrade scripts created/controlled/run?

Forget all that crap about naming conventions, formatting and how many lines can be in a function/method/module. One rule: use whatever the existing style is in whatever it is you're editing. If you don't like somebody's style, pick it apart in a code review. The only exception might be the tabs-vs-spaces thing, if only because many editors/IDEs will blindly convert one to the other, and then you wind up destroying your change history because every line was changed.

share
add comment

I think there are actually two things to address, and I would in fact consider them separately because they cannot be approached in the same manner, though I find both important.

  • The technical aspect: which aims at avoiding risky or ill-formed code (even if accepted by the compiler/interpreter)
  • The presentation aspect: which concerns itself with making the program clear to readers

The technical aspect I qualify of Coding Standard, as do Herb Sutter and Andrei Alexandrescu with their C++ Coding Standards. The presentation I qualify of Coding Style, which includes naming convention, indentation, etc...

Coding Standard

Because it is purely technical, a Coding Standard can be mostly objective. As such every rule should be supported by a reason. In the book I referred to each item has:

  • A title, simple and to the point
  • A summary, which explains the title
  • A discussion, which illustrate the issue of doing otherwise and thus states the rationale
  • optional Some examples, because a good example is worth a thousand words
  • optional A list of exceptions for which this rule cannot be applied, sometimes with work arounds
  • A list of references (other books, websites) that have discussed this point

Rationale and Exceptions are very important, as they summarize the why and when.

The title shall be explicit enough that during reviews one only need to have a list of titles (cheat sheet) to work with. And obviously, group the items by category to make it easier to look out for one.

Sutter and Alexandrescu managed to have a list of only a hundred items, even though C++ is deemed hairy ;)

Coding Style

This part is generally less objective (and can be downright subjective). The intent here is to guarantee consistency, because this helps maintainers and new comers.

You do not want to enter a holy-war about which indentation or brace style is better here, there are forums for this: so in this category you do things by consensus > majority vote > arbitrary decision by leader(s).

For an example of formatting, see the list of options of Artistic Style. Ideally, the rules should be clear and complete enough that a program could rewrite the code (though it's unlikely you'll ever code one ;) )

For the naming convention, I would try to make class/types easily distinguished from variables/attributes.

It is also in this category that I classify the "measures" like:

  • prefer short to long methods: it's usually difficult to agree on what long is
  • prefer early return/continue/break to reduce indentation

Misc ?

And as a final word, there is one item that is rarely, if ever, discussed in Coding Standards, perhaps because it's particular to each application: code organization. The architectural issue is perhaps the most outstanding issue, screw up on the initial design and you'll be plagued by it years from now. You should perhaps add a section for basic file handling: public/private headers, dependency management, separation of concern, interfacing with other systems or libraries...


But those are nothing if they are not actually applied and enforced.

Any violation should be brought up during code reviews, and no code review should be okay if a violation is outstanding:

  • fix the code to match the rule
  • fix the rule so that the code doesn't stand out any longer

Obviously, changing a rule means getting the "go ahead" from the leaders.

share
add comment

I like the format in the Framework Design Guidelines it includes a general section and rationals for the guidelines. The most useful bit are the details which start with Do, Do Not, Avoid and Consider.

Here's an example in the section Implementing Interface Members Explicitly it has the following items (note I dropped the rationales for bervity's sake)

Avoid implementing interface members explicitly without having a strong reason to do so

Consider implementing interface members explicitly if the members are intended to be called only through the interface.

Do not use explicit members as a security boundary.

Do provide a protected virtual member that offers the same functionality as the > explicitly implemented member if the functionality is meant to be specialized by derived classes.

This creates a good general tone. By using Avoid and Consider you can allow for developers to use their judgement. Also because they're guidelines and not rules developers are likely to find them more palatable and in turn more likely to follow them.

share
show 1 more comment

No one seems to have mentioned security - in a coding standard you must have reference to secure code requirements (eg the use of input validation modules, disallowing known weak functions such as strcpy, error handling requirements etc)

share
show 1 more comment

Examples. Neatly arranged, non-trivial, close-to-real-world examples that make use of every rule. Comments (not necessarily part of the code) which part of the example follows which rule.

Templates. Not the C++ kind, but something to copy-paste and fill with live. It's much easier to get that 24-lines boilerplate comment right when you have a reference to copy from.

share
add comment

Number one feature: An absolute maximum of two pages.

This is something you want every developer to read and remember. You should not have to look up in the standard every time you need to write a new function (or worse a new line). So, keep it short and keep only the rules that really provides increased value to the final product.

share
add comment

Coding standards is really several items:

Coding conventions

  • these things don't need a reason other then "consistency of code base" for ex. to use '_' in private member variables or not.
  • there could be several correct approaches. Just need to pick one for consistency. for ex. handling errors using exceptions or error codes.

Best Practices

  • these items always need a good reason with some clear examples

for ex. Never leave empty Catch after try

try { Foo(); } catch { //do nothing }

1) If there is an exception thrown by Foo() it may cause other issues on functions that follow, that assumed that foo was successful.

2) Global error handler will not notify support team of exception when it happens on prod

  • covers the practices of "Defensive Coding", like using Asserts to test your assumptions.

Coding Environment

  • tools that the whole team uses. for ex. VS 2010, Resharper, Kiln, etc..
share
add comment

Coding standards, when written on paper, is only so much effective. I like it how Go is publishing its coding standard. It has the tool gofmt to format the program text to a format. Any debate on the coding format then will simply result as a patch to the sources of gofmt.

As for what the format should have,

  • how to name variables, macros, constants, literals, functions, etc
  • how to places {,},(,),[,] when it comes to if, function body, statement blocks for any other purposes,
  • how wide should indentations be,
  • how many characters a line of text is allowed
  • how many levels of indentations are allowed before the code is rejected/sent for refactoring
  • how many lines of code is allowed per function before it is sent back for refactoring
  • maximum number of arguments a function can take before it is sent back for refactoring
  • A few lines of comments before a function begins explaining briefly what it does, if the body is to exceed one page of on screen code; leaving how the object is achieved to the code in the function's body

When I am reading others' (C language mostly) code, if variable/function names are not intuitive in the context of the project or if it exceeds five levels of indentation or functions take more than six or seven arguments or a function runs for over two or three pages on screen, it becomes very hard to read and understand the code. When asked to do enhancements/maintenance work on it, it only adds to the difficulty. It makes me wish gofmt like program be written for every project (or even language) and every source code file be run through that program before it gets committed into the project.

share
show 1 more comment

I like the Google JavaScript Style Guide.

Its concise in its guidelines yet has details if you need them.

share
show 1 more comment

Self documenting code (comments, variable names, function names, etc.)

share
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.