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.

This question already has an answer here:

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.

share|improve this question

marked as duplicate by gnat, Martijn Pieters, Joris Timmermans, Kilian Foth, Jalayn May 15 '13 at 13:02

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

show 3 more comments

16 Answers

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);
}
share|improve this answer
4  
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 '10 at 0:04
3  
where did "somewhere" and "sort by what" end up? –  user1249 Dec 4 '10 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 '10 at 23:09
show 1 more comment

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

share|improve this answer
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 '10 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 '10 at 15:33
show 2 more comments

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.

share|improve this answer
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 '12 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 at 21:44
show 3 more comments

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.

share|improve this answer
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 '10 at 20:52
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 '10 at 16:18
show 4 more comments

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.

share|improve this answer
1  
Generally speaking though, if a macro evaluates it's argument more than once, it shouldn't be a macro. –  Billy ONeal Oct 30 '10 at 18:46
show 1 more comment

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.

share|improve this answer
add comment

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.

share|improve this answer
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. –  John R. Strohm Jun 14 '11 at 17:52
show 4 more comments

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

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).

share|improve this answer
add comment

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.
share|improve this answer
add comment

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).
share|improve this answer
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
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. –  Mike Seymour Oct 7 '10 at 15:21
show 1 more comment

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

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