views:

656

answers:

11

What are some good examples of coding guidelines. I'm not really looking for anything specific to a single language.

But what should I be doing/evaluating as I write coding guidelines? Such as how flexible should the guidelines and how much should decisions be left to the programmer or to someone else or even pre-decided by the guidelines.

This set of guidelines that I am working on is supposed to cover a wide range of topics: comments, database design, and even some user interface guidelines.

+1  A: 

In general, I would want guidelines to answer the questions that you would normally ask but would take too long to answer, and that might be "personal preference" if you were just coding alone. Usually they specify pithy things like database naming conventions and spaces vs. tabs (and how many spaces) as well as commenting / documentation comment styles.

UI guidelines are a different beast than the others I think.

One of my favorite examples of coding style guidelines is the Linux kernel coding style, although it doesn't go into the specifics that I've seen in other guides.

jamuraa
+7  A: 

It's a fairly open question, and the answer is equally as open:

Every guideline should cost less to implement than the benefit it brings.

Be careful, because each side of the equation has some hidden parts.

The cost of implementation can include excluding perfectly good alternatives, stifling creativty and innovation, and encouraging code reviews to degenerate into highlighting minor infractions of the style rather than addressing real issues.

The value of the benefits may be intangible (and hence frustrating) to a busy developer in a hurry, but might result in your organizations brand being stronger or bringing new staff onto the project being faster - something that might outweigh the small incremental cost of complying.

Oddthinking
I agree, I defiantly don't want to stifle creativity or have code reviews turn into argements of style. I want to help ensure code is maintainable and "good" code (good varying on what the language is).
jtyost2
+8  A: 
if( !codingGuidelines.Followed)
{
   reason = programmer.WhyNot();
   if( reason.Acceptable)
   {
      codingGuidelines.Integrate( reason);
   }
   else
   {
      team.GiveAssKicking(programmer);
   }
}
John MacIntyre
And what coding guidelines did you follow to produce that? Why doesn't your reason variable have a type or a prefix?
BenAlabaster
I started to, but then realized I was taking this answer a little to serious.
John MacIntyre
A: 

Coding guidelines are behavioural rules for your teammembers, so that you can read eachothers code without too much trouble.

It also gets the "bracket on newline or on same line" discussions out of the way at your code review sessions, which saves a lot of time ;-)

When writing code guidelines, make sure that they're there for a reason, and that they actually help your team on writing more readable code.

Rolf
+2  A: 

Coding guidelines are there to make it easy for others to read your code. Even if you are writing code for yourself and are the only developer, it may be useful to find a set of guidelines commonly accepted in the industry and stick to them. It will make it easier for you to read other peoples code and for you to fit into a larger team at a later date.

If using .net, take a look at StyleCop. By default it contains standards that MS use themselves and used to design the .net framework around. You can get it from here:

http://code.msdn.microsoft.com/sourceanalysis

You can disable rules you don't like and add your own. It can even be scripted to enforce the rules when code is checked in. The great thing about it is that if you're really new to this sort of stuff, it will tell you exactly what you're doing wrong. If you want to go one step further, take a look at Resharper. It's the same sort of thing, but does it in real time as you type (though by default it uses a slightly different standard.

I'm sure there are similar utilities around other languages if c# is not your thing!

DaEagle
Not using .NET, PHP/CSS/XHTML/SQL/JS but good suggestion.
jtyost2
I've always wondered why more language definitions don't include a canonical transformation from abstract syntax back to concrete syntax. That plus a tool using those rules and the parser to canonicalize concrete syntax would cut a lot of these "where does the whitespace go" type debates off at the start.
Doug McClean
@Doug, if you had asked me in 1992, I would have pointed to existent tools that *almost* did that, and predicted everyone would be using tools as you describe by the turn of the century.I picked that one wrong!
Oddthinking
+4  A: 

As a developer, I generally prefer guidelines to give basic guidance, but not be so strict that I can't code how I like... for instance, if a guideline is telling me what coding patterns must be used rather than allowing me to make my own professional judgement then it's too tight:

For example, these are the type of things I might expect to see:

  • Style of variable names i.e. hungarian notation(not that I strictly use those)
  • Methods should be commented with their general purpose, including what they return (if anything)
  • Classes should be defined with a specific layout: i.e. all private fields at the top, followed by events, public methods, private methods, whether they should be in alphabetical order
  • Naming conventions for namespaces, classes, methods, events and properties etc

You get the picture. I shouldn't be restricted to stuff like:

  • Thou shalt use If notation instead of int a = (blah)? true : false;

Coding styles obviously need to be common across a team to allow developers to be able to work together effectively. You can't have one person way out there in left field using complex mathematical algorithms that nobody else on the team can understand and have another way out in right field who can barely comprehend the implementation of interfaces. So as a rule of thumb, they should be designed to help keep your team together while not dampening productivity and creativity.

Get some input from your development team as a whole so that a "house" standard can incorporate everything it should and not include a bunch of stuff it shouldn't.

BenAlabaster
+1  A: 

Juval Lowy's C# coding guidelines is an excellent example of a proper guideline. I have a couple of things I'd change in it, but for the most part it's fantastic.

Terry Donaghe
+2  A: 

I want a coding standards document to resolve religious arguments for the team.

For the questions where there are multiple worthwhile answers, and people have a tendency to argue about them for a long time, we want to get consistency across the whole project and avoid spending much time discussing them.

Good examples are "TABs vs. Spaces" and "K&R vs. ANSI brace placement". Take a poll in the team, make a decision, and write it down. Apply the decision to all your existing code at once, and check it in by itself. Never discuss it again.

Jay Bazuzi
Ironically, I just posted to say brace placement doesn't matter (just make sure they're present). But I agree wholeheartedly on the whitespace issue.
Tom
A: 

I also like the idea of a coding style helping developers to visually identify bad/buggy code. For example, including the type of a variable in its name can help down the road if someone should accidentally assign an int a float value or something like that.

abramN
+21  A: 

There are generally three purposes for coding standards:

  • Reduce the likelihood of bugs
  • Reduce the time required to analyze code written by someone else
  • Give someone a power trip

Obviously, the third is a waste of everyone else's time, but you do need to consider it, specifically so you don't go down that road.

Having said that, there are some definite do's and dont's that I've noticed:

  • Enforce consistent whitespace usage. Tabs, 2-spaces, 4-spaces, doesn't matter. Keep it consistent, so indent levels aren't screwed up by people using different editors. I've seen mistakes made because maintenance programmers misinterpreted the nesting level of a block of code.
  • Enforce consistent logging methodology. It's a huge drain on support staff's time if they aren't able to skim over logs, because everyone's module logs for different reasons, and everyone has a different definition of Info vs. Warning vs. Error.
  • Enforce consistent error handling. If module A throws exceptions, module B returns error codes, and module C simply logs and moves on, it'll be a pain to integrate them without letting an error slip through the cracks.
  • Try to avoid petty things like placement of curly-braces. That's going to get a lot of people arguing over their pet style, and in the end, it really doesn't have a huge impact on the readability of code. On the other hand, enforcing the presence of brackets can make a difference.
  • When integrating disparate code bases, don't be tempted to change everyone's variable naming conventions to match the golden standard. You may have a standard for moving forward, but what's most important is that any localized standards that already exist are preserved consistently. If one module uses m_member, a maintenance programmer should be using m_member2 rather than applying any other standard (such as member2_ or m_lpcstrMember2 or whatever). Local consistency is king.
  • Filesystem layout is important. Keep it consistent. Make it easy for someone to jump into a library sourcebase and instantly know where are the headers, the Makefile, the sources, etc. If you're working with Java or Python, this is a no-brainer because the package system enforces it. If you're working with C, C++, or any other myriad of scripting languages, you'll need to devise a standard layout yourself and stick with it.
  • Don't sweat the little stuff. Variable naming conventions, spaces between parentheses or keywords or function names... most of that doesn't matter, because it doesn't reduce the likelihood of a mistake. Every rule you set should have a concrete rationale, and you shouldn't be afraid to change or remove it if you discover it's causing more grief than it's worth.
  • Don't enforce gratuitous comment blocks everywhere. They'll end up as a waste, and most comments are better off being expressed in the code itself (as variable or function names, for example).

Finally, the most important thing is to have regular code reviews between peers. Encourage people to speak up when they see a "code smell." Also be sure people realize that constructive code criticism is not meant to be personal - the source is shared by everone on the team, it doesn't just belong to the original author. In my experience, the most heinous problems have been design problems that wouldn't have been solved by any amount of coding guidelines. Software design is still something of an art form (for better or for worse), and a pool of brains is much better than a single one.

Tom
Great answer Tom.
jtyost2
"Pool of brains".... Just the image I need first thing in the morning
Ken
Thanks Tom, very helpful. +1
philippe
+1  A: 

Code Complete is an excellent book on general programming best practices and guidelines that can be applied to any language.

It covers all aspects of programming and is a must read for the practical programmer who wants to do things the "best" way for each problem encountered.

Jason