30

I work in a control systems company, where the primary work is SCADA and PLC, along with other control systems stuff.

Software development is not really something the company does, apart from little bits here and there, until there was a decision to create an internal project management and appraisal system.

This project has been taken on by people who came here as software people originally and we are mostly junior.

The project started off small, so we only documented stuff like design, database stuff etc, but we never really agreed upon a coding format/conventions.

We started using StyleCop to make sure we had well documented code, but I feel we need an official document for coding conventions/practices so we can continue a good standard and if there is any more major development work in the future, whomever works on it has a good baseplate.

Therein lies the problem, I have no idea how to draft up a document for coding conventions and standards, all I can think of is examples of good vs bad practice (for example camel case when naming variables, avoiding Hungarian notation etc) we are all competent enough programmers (apparently) but we just don't have a charter for this kind of stuff.

To put a point on it, my question is: What are the key aspects and contents of a good coding standards document?

9
  • 3
    Do you already have comprehensive test coverage? Doesn't matter how pretty the code is if it is wrong... Commented May 1, 2013 at 12:14
  • 2
    The good thing is we throughly test our stuff, we have regular unit testing implemented for our project, and we before releases we will use random hallway testing, and write a test spec for black and white box testing.
    – Felix Weir
    Commented May 1, 2013 at 13:26
  • The priority our little group holds is our code is robust and can't be broken. We also use bugzilla for bug tracking, and a custom bug reporting tool for users.
    – Felix Weir
    Commented May 1, 2013 at 13:32
  • Here are some resources considered "classic" works on the subject. I would suggesting taking the best parts of these standards to make a document that meets your group's needs: 1. Bell Labs, Indian Hill C Style and Coding Standards, 19 February 1997, maultech.com/chrislott/resources/cstyle/indhill-cstyle.pdf 2. Stallman, Richard, GNU Coding Standards, 30 June 2012, gnu.org/prep/standards/standards.html 3. Jet Propulsion Laboratory, JPL Institutional Coding Standard for the C Programming Language, Version 1.0, 3 March 2009, lars-lab.jpl.nasa.gov/JPL_Coding_Standard_ Commented Nov 25, 2015 at 0:17
  • 1
    Anything that can be automated MUST be automated. Tabs, spacing, blank lines, formatting: All of these can be automated. Better, every self-respecting source code control system allows automated steps to be inserted at check-in, so you can automatically force your correct formatting every single time a module is checked into the repository. This lets the programmers concentrate on actually getting the code right, instead of counting spaces. Commented Feb 23, 2022 at 14:36

6 Answers 6

34

What are the key aspects and contents of a good coding standards document?

  1. Being supported by tools which enable automated checking of the code. If I know that I can't commit to version control any piece of code which doesn't match some rules, I would be encouraged to follow those rules in my code. If, on the other hand, some fellow programmer have written somewhere that I need to follow a rule, I don't give a crap about those rules.

  2. Being well thought-out, instead of being your personal opinion. You don't plainly say: "from now on, we don't use regions any longer, because I don't like regions." Rather, you would explain that regions encourage code growth and don't solve any major problem.

    The reason is that in the first case, your fellow colleague would answer: "well, I like regions, so I would still use them". In the second case, on the other hand, it would force people who disagree to come with constructive criticism, suggestions and arguments, eventually making you change your original opinion.

  3. Being well documented. Lack of documentation creates confusion and room for interpretation; confusion and possibility of interpretation lead to style difference, i.e. the thing standards want to suppress.

  4. Being widespread, including outside your company. A "standard" used by twenty programmers is less standard than a standard known by hundreds of thousands of developers all around the world.

Since you're talking about StyleCop, I suppose that the application is written in one of the .NET Framework languages.

In that case, unless you have serious reasons to do differently, just stick with Microsoft's guidelines. There are several benefits in doing it rather then creating your own standards. Taking the four previous points:

  1. You don't need to rewrite StyleCop rules to fit your own standards. I don't say it's hard to write your own rules, but if you can avoid doing it, it means you have more time doing something useful instead.

  2. Microsoft's guidelines are very well thought. There are chances that if you disagree with some of them, it might be because you don't understand them. This was exactly my case; when I started C# development, I found a few rules totally dumb. Now, I completely agree with them, because I finally understood why they were written this way.

  3. Microsoft's guidelines are well documented, so you don't have to write your own documentation.

  4. New developers who will be hired in your company later may already be familiar with Microsoft's coding standards. There are some chances that no one will be familiar with your internal coding style.

7
  • We have version control (SVN, hoping to move to GIT soon), and the lead of the project always reminds us to regularly update then commit to avoid mass conflicts (at least a couple of times a week).
    – Felix Weir
    Commented May 1, 2013 at 13:30
  • BTW, you mention "tools which enable automated checking", which tools are these? I am curious.
    – Felix Weir
    Commented May 1, 2013 at 13:30
  • @FelixWeir: for .NET Framework? StyleCop. Commented May 1, 2013 at 14:06
  • Oh right, I thought you were hinting at something else. We use Stylecop... :^)
    – Felix Weir
    Commented May 1, 2013 at 14:28
  • 1
    @FelixWeir: also, try (if you haven't done it already) Code analysis. The purpose is different and not related to style itself, but it also enables standardization. Commented May 1, 2013 at 14:46
12

The first important thing to note is that a coding standards document is not about right and wrong. It's not about good and bad or which method is better.

A coding standards document's purpose is to make sure that all code is designed, written and laid out the same to make it easier for a developer to switch from one persons work to another without the needed change of mentality to read someone else's style.

It's all about uniformity, and nothing about "Right and wrong"

With that in mind some things you should clarify in a coding standards document are:

Naming Conventions

How will you name your methods, variables, classes and interfaces? Which notation will you be using?

Also something else included in our standards was a split off standards for SQL, so we had similar names for tables, procedures, columns, id fields, triggers, etc.

Indentation

What will you be using for indentation? A single tab? 3 spaces?

Layout

Will braces be kept on the same line as the opening method line? (generally java) or on the next line or a line of its own? (generally C#)

Exception Handling / Logging

What are your standards for exception handling & logging, is it all home grown or are you using a third party tool? How should it be used?

Commenting

We have standards to dictate grammatical correctness, and that comments begin on the line before, or after, not on the same line, this increases readability. Will comments have to be indented to the same depth as the code? Will you accept those comment borders used around larger texts?

How about the \\\ on Methods for descriptions? Are these to be used? When?

Exposure

Should all of your methods and fields be implementing the lowest level of access possible?

Also an important thing to note. A good standards document can go a long way in helping review code, does it meet these minimum standards?

I've barely scratched the surface of what can go into one of these documents, but K.I.S.S.

Don't make it long, and boring, and impossible to get through, or those standards just wont be followed, keep it simple.

5
  • 1
    Coding standards often, especially for C/C++ development, also contain a (large) section about which language constructs you should not be using and why. Commented May 1, 2013 at 12:56
  • 3
    @BartvanIngenSchenau there's no reason why you need them for C++, or why you don't need similar sections for other languages - you can make a mess out of C# or JS or .. well, anything. All languages have 'features that can be misused'. Best to train your devs to be good at their job instead of filling the standards document with "how not to code" mini tutorials.
    – gbjbaanb
    Commented May 1, 2013 at 14:54
  • @gbjbaanb: I can't comment on other languages, but C++ has enough dark corners and pitfalls that it is not about avoiding mis-use, but rather steering people away from the features that are difficult to use correctly (for example, overloading of &&). Training is good, but sometimes it is better to have a nice reference document to refresh your memory why you should not do that. Commented May 1, 2013 at 15:35
  • 1
    @BartvanIngenSchenau i feel that would be better placed in a Coding Guidelines Document, not a Coding Standards Document
    – user78252
    Commented May 1, 2013 at 15:39
  • @RhysW: Fair enough. My experience is that the two are usually combined in one document (titled 'Coding Standard'), but I don't see having it in two documents as a problem. Commented May 2, 2013 at 8:14
8

I hate most standards documents as they usually try to sweat the small stuff and ignore the bigger picture.

For example, nearly all of them will say how to name variables or place brackets. This is pure style and does little to really help a group of devs code correctly. They ignore stuff like directory structure and code layout. I've seen standards documents that told you exactly how many spaces to put between operators and how many blank lines to put between methods. All of these usually end up with a ton of exceptions to the rule which just shows how pointless they really are, and then they are so big no-one can follow them, which again, makes a mockery of the point they are trying to make.

Now for me, I use many different bits of software from lots of different people and they all have different styles. I simply get used to this, I don't complain that there isn't a common style across all development groups. As long as the code is a common style throughout a project, I really don't care what that style is. So my first rule for all standards documents is: Keep a consistent coding style within the project. no-one should give a fig where the brackets are, as long as they are all the same. Take the religious wars and shove them :)

The second is code layout. When I pick up a piece of code, I want to see that its laid out along similar lines as other, similar pieces of work. If I have a web service I want the name of the wsdl contract to be clear, I want the name of the implementation to be clear. I do not want someone to come up with a brand new and different layout for files and classes. That means I have to play "hunt the code" which is a nuisance. If it looks the same as the last project I worked on, I can immediately know where to find what I'm looking for and it is probably the biggest help to working with other people's code that I know. So, keep a structure of how the code is laid out (eg Documentation folder for docs, interfaces for interfaces etc - whatever it is that works for you, but stick to it).

Code artifacts should be present too, so you need to say whether the expected error handling is exceptions or error codes - ie. document architectural functionality that's in use. It should also say what kind of logging to use and how to present logs/error handling to the user or whatever subsystem is used to manage code in the wild. I worked in a place where every project did logging differently - it was pathetic how each code release had to have its own, different, operations document telling the ops guys how to tell if it had gone wrong. Event log, log file (in which case where), etc are all valid here. The same applies to other common aspects to code - how to configure it (no point using a .config file for some programs, or a custom DB, or command line params, or registry for others).

In short, the only thing that matters is Consistency. And as huge standards documents are too much to read and memorise, I prefer to just inform people of the stuff they cannot see (eg architectural standards like logging) and tell them to keep the code they write consistent with what is currently there. And if you don't have code already then you don't need a standards document! (well, not until you've written enough to make it useful).

So take from that the main points: don't try to make a legal document, think of things that aren't just coding but also how the code works and how the code fits with other people's expectations. Then trust people to do good code and you'll see that they do. (and if they don't you can have words with them, no need to lay it down like law).

2
  • I think what you write is correct but you contradict your self. You mention consistency and some example of it ("code is a common style throughout a project, I really don't care what that style is. ") Yes but that's the whole point right ? :D Not everyone has common sense or "your-common-sense" and therefore that's why yo need a damn legal document. The more the team the less is likely to follow the 'consistency' of the rest (and bigger the project decrease chances too). Commented May 25 at 6:04
  • The legal document is not there to 'read' is there to tell "hey! this is our agreement and you dont follow it, is WRITTEN down and you HAVE NO EXCUSE". Same as ANY other 'document' / 'contract' in this society. Who reads the whole thing before signing really? no one. that document is there when something happens. In our case, if some dev doesnt have a common sense, and follow consistency then you can use that to point out that is "out standards". Sure you can just say by voice but again.,. large the code base --consistency. (and that's why there are linters, and so on..) Commented May 25 at 6:06
7

I was going through this process multiple times. And the most successful (although bumpy anyway) approach was to take a "Coding Standards" document from a well known company and modify it to fit your needs.

For example, I just found this one: http://www.tiobe.com/content/paperinfo/gemrcsharpcs.pdf

Anyway, keep your flame-thrower handy.

Cheers,

1
3

Don't, it's an utter waste of time and energy. StyleCop is great and was established over years by people far more experienced and way smarter than you or anyone on your team. Embrace and love it! It guides you continuously, which is better than any document waiting for someone who can be bothered to read it.

1
  • Limited to C#, whereas the guide should discuss a framework for good coding practice and then point to something like StyleCop (the "how").
    – user257667
    Commented May 18, 2020 at 16:10
3

Here's an example. I started with a template someone else wrote, but I can't find it, so here it is as I've edited:

Source: https://gist.github.com/earonesty/ccee25a56be7adeb5f670cf44e5fa479

Coding Guidelines

General

  • These are not to be blindly followed; strive to understand these and ask
    when in doubt. Sometimes standards are a bad idea.

  • Don't duplicate the functionality of a built-in library.

  • Really try hard not to duplicate the functionality of an existing maintained library or function. If this means making a new repo to share across projects... please do that... even if it's a simple function.

  • Don't swallow exceptions or "fail silently."

  • Don't write code that guesses at future functionality. (Don't be an architecture astronaut)

  • Use callbacks, passed objects and/or split the repo up into multiple repos to prevent tight coupling across directory boundaries. Especially avoid cross-importing.

  • Never use IPC where importing a class will work. If that class comes with too much baggage, break it up and import the stuff you need.

  • Strive to adhere to the Unix Philosophy. There are some nice articles that discuss this philosophy as applied to object oriented code:

New Projects

  • Master branch must require code reviews and passing tests

  • All new projects must have a full CI pipeline, including linters, tests

  • Coverage enforcement is required

  • If a project has dependencies, it must use and commit a lockfile of some sort

Object-Oriented Design

  • Avoid global variables & long parameter lists

  • Limit dependencies of an object (entities an object depends on).

  • Limit an object's dependents (entities that depend on an object).

  • Prefer composition over inheritance.

  • Prefer inheritance over callbacks and branches.

  • Prefer small methods. Between one and five lines is best.

  • Prefer small classes with a single, well-defined responsibility. When a
    class exceeds 100 lines, it may be doing too many things.

  • Tell, don't ask.

Opening files, using API's:

  • No system should ever hit the internet/connect to network bed, open a file that might be on a network drive, etc. ... as a precondition for startup. Missing network/internet needs to be gracefully handled.

  • When opening a file or reading data from the internet in any way, or even assume it contains deliberately constructed malicious data. Write a test to prove that appropriate exceptions are thrown, and are gracefully handled.

  • When doing IPC, assume the other service can be down. Ensure timeouts & failures are handled.

Python

  • Avoid putting any real logic in del override

Javascript

  • Start new projects with Typescript

  • Use maps, not objects, as much as possible.

Testing

  • Don't test private methods.

  • Use intermediate assertions about state during test progression.

  • When at all possible, put your debug logs in the test, not in the code.

  • Use both integration tests and unit tests not one or the other.

  • Don't evade coverage checks.

Relational Databases

  • [Index foreign keys].

  • Constrain most columns as [NOT NULL].

  • In a SQL view, only select columns you need (i.e., no SELECT table.*).

  • Use an ORDER BY clause on queries where the results will be displayed to a
    user, as queries without one may return results in a changing, arbitrary
    order.

  • Never put meaningful or computed data in the "id" or "primary key" field of a table.

  • Sqlite need not be considered a "relational database", depending on what you're doing with it.

    • Use as key-value store is OK

    • Use as indexed "blob storage" instead of filesystem is OK

CI/CD & Scripts

  • No complex bash scripts.   Scripts that are complex enough to need stuff like functions and loops should be moved into a language suitable for complexity and testing, like python or node.

  • No one-off complex scripts.  Scripts that manage deployments, requirements, etc should, ideally be abstracted and run in many projects.... rather than each project having its own requirements, versioning and deployments systems.   This is especially true for libraries.

Web

  • Avoid rendering delays caused by synchronous javascript hits.

  • Use HTTPS instead of HTTP when linking to assets.

  • Use UTF-8 only

Changes to this document

To add new standards:

  • First make sure your proposal doesn't suck. Coding standards that suck have the following attributes:

  • Open up a slack discussion with at least 3 other devs and propose one or more additions or changes. Include the CTO and the Engineering Manager.

  • Edit this page with the verbiage everyone agrees on.

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