32

In response to This Question, I ask: What are the best parts of your coding standard?

What are the best practices that help with code quality, reliability, maintainability, readability, etc.

Please include the language, the item from the standard, and the reason it improves your code.

3
  • Related to: programmers.stackexchange.com/questions/1323/… but I think this is different, though. Sep 10, 2010 at 19:37
  • That one asks 'should you have one?' I know you should have one, I want to know what should be in it...
    – AShelly
    Sep 10, 2010 at 19:41
  • If you can vote and think this is a useful question or it have useful answers below, please vote up. StackExchange sites need votes to build a good community. You can give 30 votes per day, don't waste them. Specially users with high reputation and low counting votes given please read this: meta.programmers.stackexchange.com/questions/393/…
    – Maniero
    Oct 5, 2010 at 19:29

16 Answers 16

23

All Languages: Write readable code instead of comments

  • A comment followed by a block of code can be replaced by a method which states the intent just as well as the comment, and makes the code more modular and reusable as well.
  • It makes refactoring happen more often.
  • It helps us write simple, readable clean code. Readable code is a joy to work with.
  • It tends to make methods short and sweet.
  • It avoids comments getting out of sync with the code
  • It challenges you to rewrite commented code that is hard to understand.

Compare this:

public void update() {
  // Fetch the data from somewhere
  lots of lines of;
     code;
     for;
       fetching;
     data;
  from somewhere;
  // Sort the data
  more lines of;
      code;
         which sorts;
         stuff;
      around;
  a bit and then;
  // Update the database
  lines of code;
      which uses;
         some lib;
         to update;
            using iteration;
            and logic; 
      the database;
  done;
}

With this version where comments are replaced with function calls:

public void update() {
    data = fetchData();
    sorted = sortResults(data);
    updateDatabase(sorted);
}
4
  • 5
    I disagree to some extent. I have to deal with too much code where the function names are vague, ambiguous, or misleading, and to figure out what the code actually does, you always have to go to that method anyway. Just looking at your second example, it's extremely unclear what the code does. Hopefully you'd use more concrete names in practice.
    – Jacob
    Nov 13, 2010 at 0:04
  • 3
    where did "somewhere" and "sort by what" end up?
    – user1249
    Dec 4, 2010 at 23:00
  • 3
    Indeed. In my oppinion there are three ways to write code: 1) write unreadable code. 2) write unreadable code and comment it readable. 3) write readable code.
    – hlovdal
    Dec 20, 2010 at 23:09
  • @hlovdal: Excellent quote, I'm gonna borrow it :) Dec 21, 2010 at 7:57
12

Just one public class must be put in each file, no more.

4
  • 5
    I despise this one when I use an API designed this way. It forces me to write tons of import statement boilerplate to use a bunch of classes that are naturally related and search four zillion auto generated documentation files to find what I'm looking for. From an API usability perspective I much prefer coarser grained imports.
    – dsimcha
    Sep 27, 2010 at 23:09
  • 2
    It'll depend on the language but in C# this is definitely the route to go. SRP plus one file per class results in very few 'false positive' merge conflicts if you're working in a team. It also has no impact on the API (that can be simplified with facades for example)
    – FinnNk
    Oct 30, 2010 at 15:33
  • @FinnNk: So this rule is about source code control management? Also, what is a facade? Nov 13, 2010 at 1:30
  • No, but following SRP means that if two people are working on different things then their code is less likely to result in merge conflicts. The rule has nothing to do with scm but simplified scm is a by-product. The comment about facades was aimed at dsimcha's comment about wanting coarser grained imports for api's. See en.wikipedia.org/wiki/Facade_pattern for definition.
    – FinnNk
    Nov 13, 2010 at 10:17
9

Any Language:

Adequate and consistent use of whitespace, both vertical and horizontal, vastly improves the ability of the code to be rapidly skimmed as well as read at a normal pace. I'm not going to argue about tabs versus spaces, as long as their usage is consistent, but proper indentation and judicious use of blank lines and spaces around operators are all absolutely necessary.

Related: keeping line lengths to a reasonable limit such as 80 columns has demonstrable benefits: no weird wrapping on consoles, no need to scroll, and the ability to view multiple files side by side on a wide monitor, not to mention that it tends to help encourage refactoring of deeply-nested code and run-on expressions.

5
  • spaces should be favored over tabs at all times for portability, tabs look different from one terminal or editor to another, but spaces are always one character each. Sep 6, 2012 at 2:37
  • 1
    @JimmyHoffa: I prefer spaces as well, but I’ll play devil’s advocate and point out that looking different is the point of using tabs—I can (setq tab-width 2) in Emacs and my buddy can set tabstop=4 in Vim and everybody’s happy. It’s akin to the difference between hard and soft wrapping.
    – Jon Purdy
    Sep 6, 2012 at 17:38
  • 1
    @JonPurdy: Definitely, though I'd also say that the main time where spaces have an advantage is when lining up parameters with an open paren, which I and many others who use tabs don't do because method name lengths vary, and code indentation levels (imo) shouldn't.
    – Magus
    Feb 27, 2014 at 21:44
  • @Magus: Sure, then again I am allergic to alignment even when using spaces exclusively, because it tends to make for bad diffs and blames, and makes style-preserving automated refactors more difficult.
    – Jon Purdy
    Feb 27, 2014 at 21:58
  • Agreed. It's just the most common argument for spaces. I don't believe in it at all.
    – Magus
    Feb 27, 2014 at 22:04
7

C#: Differing naming styles for different types of names.

For example:

public class ClassNamesArePascalCase{
    public int FieldsArePascalCase;
    private int _privateFieldsAreUnderscoredCamelCase
    public const int CONSTANTS_ARE_CAPITAL = 3;
    
    public void MethodNamesArePascalCase( string parametersAreCamel ){
        int localVariablesAreCamel;
    }
}

It doesn't matter so much which standards you use for which name types, as long as it's consistent among that type (eg, all constants are capital), consistent within the project, and different from eachother. The benefit here is that I can tell at a glance that _someVar is a private field without having to look it up.

6
  • 2
    This is by no means a style unique to C#. Most C++, Java, and C programmers have a similar style rule.
    – greyfade
    Sep 10, 2010 at 20:52
  • I'm aware- that's just the language I was using when that standard was imposed on. You are correct that it is appropriate to many languages. Sep 10, 2010 at 21:55
  • I use camelcase for private variables and single underscore pascal case for members used by properties. Also, since properties are the like a combination of public variable and method they're also pascalcase. Sep 12, 2010 at 1:04
  • 2
    I agree in general but disagree on the "constants are capital" rule. I think this type of rule evolved from misapplying the C "preprocessor macros are all caps" rule (which makes sense, it's a dangerous construct and all caps makes it stand out). I don't think it adds any value to be able to tell whether a given symbol is constant or not and it conflicts with the other rules: "is this a private or public constant?" naming rules are a good thing, but they should take the language's capabilities into account and not just be dragged from one language to another whether they make sense or not.
    – Ferruccio
    Oct 7, 2010 at 16:18
  • @Ferruccio looks like you're right. Here's the link to the common C# capitalization conventions msdn.microsoft.com/en-us/library/x2dbyw72(v=VS.71).aspx. Nov 14, 2010 at 13:57
6

C: Preprocessor macro 'functions' should be in all caps

Example: #define CUBE(x) ((x)*(x)*(x))

Reason: When scanning code, Macros stand out from regular functions, and alert you that there may side effects a normal function call would never have, like changing the value of the "input" argument, or having it evaluated 3 times.

2
  • 1
    Generally speaking though, if a macro evaluates it's argument more than once, it shouldn't be a macro. Oct 30, 2010 at 18:46
  • Billy is correct, try this: int i,j; i=1; j=CUBE(i++);
    – Jay Elston
    Jun 14, 2011 at 18:54
5

In Java.

  • Invoke the Eclipse source code formatter automatically every time a file is saved.

This means that source code changes are registered at the first commit afterwards, instead of some later time when a reformat is done. This is good when doing "when was this changed" investigations.

5

Never use Hungarian Notation. In statically types languages it's unnecessary, and in dynamically typed languages it's almost always harmful. Also, Hungarian Notation is the tactical nuclear weapon of source code obfuscation techniques.

5
  • Please elaborate on why it's harmful in dynamically typed languages.
    – Kyralessa
    Jun 14, 2011 at 17:44
  • 1
    @Kryalessa, Hungarian notation statically encodes the type of the variable in the variable name. In a dynamically-typed language, the static type encoding is probably wrong. Jun 14, 2011 at 17:52
  • What John R.Strohm said. Also, in dynamically typed languages one usually uses duck typing, where there might not be just a single type to be encoded in a variable name. If you try to encode all the possible types into a variable name, you're likely to end up with something like list_or_set_or_deque_or_string. Jun 14, 2011 at 19:49
  • so IMyInterface should be banned? and so should _privateVar? (although _ doesn't explicitly say 'private' it is used as a convention nowadays). sometimes these hints are good to have which is exactly what Hungarian was all about. (sure, overuse is very bad, so 'genymdhms' is still not good practice by any means but pXXX (for pointer) is)
    – gbjbaanb
    Jul 4, 2011 at 16:05
  • @gbjbaanb: I'd argue that they should both be banned, considering that a decent IDE can color them distinctly. However, in languages like C# and Java, the interface prefix is a standard part of the BCL, so it may as well be followed.
    – Magus
    Feb 27, 2014 at 21:50
3

C#: Use Extract Method instead of comments

If we felt like we needed to add a comment to a block of code to explain what it's doing, instead we would extract that code into a new method with a descriptive name.

This makes the code more readable and modular, and reduces the number of (out-of-date) comments floating around.

3

Formatting - especially Indentation! I'm using Delphi and the first thing to do when I get code not formatted to my usage I reformat it. The built-in formatter in Delphi serves as one of the most used fetaures in these cases.

3

CONSISTENCY

I'm not bothered by any particular naming or coding conventions (though, I obviously have preferences) as long as whatever codebase they're applied to uses those conventions consistently.

I've been going through Clean Code lately, and I find that it's helped me a fair bit (though I don't agree with/use all of it).

1

For C++ inheritance. Pointing out that,

  • Multiple Inheritance: Only very rarely is multiple implementation inheritance actually useful.

For other things.

  • Preprocessor Macros: Be very cautious with macros. Prefer inline functions, enums, and const variables to macros.
  • Smart Pointers: If you actually need pointer semantics, scoped_ptr is great. You should only use std::tr1::shared_ptr under very specific conditions, such as when objects need to be held by STL containers. You should never use auto_ptr.
1

C# and Java:

  • Making sure logging of critical sections is properly defined (log4*).
  • Keep methods and classes small (Single Responsibility).
  • TDD or writing unit tests for important sections of business logic (jUnit or nUnit).
1

SQL

We used a naming convention for our database elements.

  • tblTableNames
  • viewViewName
  • spAdminProcedureName
  • spProcedureName

Oftimes we would create a widget for a customer and 3 months later we would resell that widget to another customer. Eventually naminging conflicts arose and we had to recode a widget.

For example:
Press Release Widget

  • tblContent
  • tblCategories
  • tblImages

Photo Gallery Widget

  • tblPhotos
  • tblCategories

If Customer-A already had the press release widget and now wanted the Photo Gallery widget we had a naming conflict with tblCategories. We couldn't just script the Photo Gallery elements and run them against Company-A's database. Argh!

So we we started appending a "widget" references to our SQL elements:

  • tblPG_Photos
  • tblPG_Categories
  • tblPR_Content
  • tblPR_Categories
  • tblPR_Images
  • spPG_Proc1
  • spPG_Proc2
  • spPG_Proc3
  • spPR_Proc1
  • spPR_Proc2
  • spPR_Proc3

This kept things nicely bundled and helped us be more profitable in the long run.

0

Unique naming method, does not matter on the language. For example.. G = Global, L = Local ,P = Parameter. Now when you have a variable like G_strFoo I know that it's definition can be located in my global file. Helps with keeping up with all the variables in my programs.

2
  • 3
    This is only useful as compensation for bad design. By avoiding globals, and implementing small classes and functions each with a single, well-defined purpose, the scope, type and purpose of a variable will be clear without pseudoHungarian tags. Oct 7, 2010 at 15:21
  • yeah, get rid of I for Interface!
    – gbjbaanb
    Jul 17, 2011 at 21:29
0

In Python, use only the standard library, and if you can't avoid using another library, explain why somewhere. Someday that lib may need to be replaced and it would be nice to know where to start.

Also, keep it very very simple.

0

I wrote about this in my blog the other day.

C# Coding Conventions and Standards

http://www.codehustle.com/2011/06/c-coding-conventions-and-standards.html

I think as far as coding conventions go, the primary thing that contributes to the reliability, maintainability, and readability of code is naming conventions. The rest of the stuff is pretty standard.

There is not one "right" or "wrong" way with naming conventions. The key is consistency. For example, I always use camelCasing for parameters and local variables, I use camelCasing prefixed with an underscore for private / protected field members, and I use PascalCasing for class names, properties, events, functions, etc.

I generally shy away from hungarian notation as well for the sake of readability but I do think that in some scenarios it is helpful (I usually use hungarian notation for GUI types).

One side effect of sticking to conventions is that it is easy to keep track of what type of identifier you are looking at when reading code. For example, I can always rely on the fact that properties utilize PascalCasing while local variables do not, which saves me from having to scan back and find the definition of an identifier when reading code.

Having your team follow the same coding conventions and standards can help make your software more readable and more uniform by keeping things consistent and clean. This facilitates maintainability by allowing members of your team to be able to read and comprehend code written by co-workers more quickly without having to mentally run a background filter to interpret layout and style differences, etc. It also fosters best practices and can contribute to keeping your APIs consistent as well.

If your code is clean, consistent, and easy to read, it becomes more maintainable and less error prone.

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