Tuesday, October 05, 2004

Programming styles I use and why....

When the code you write is for the benefit of others, a clear and readable coding style is as important as a good prose style. This is my personal style guide which I use in all my programming.

#1 Naming conventions.

Concise naming is important if code is consumed by someone else. Cryptic names for variables, methods and properties are for obfuscators, not programmers.

Private Fields begin with an underbar and a lower case letter such as _data. Long names are CamelCased such as _myLongData.

Accessor properties remove the underbar and capitalize the first letter such as Data or MyLongData.

Variables in a method begin with a lower-case letter and are camel-cased if long such as "variable" or "myLongVariable". Parameters passed to a method follow similar convention.

Class names begin with capital letters and are camel-cased where necessary.

Class, method, property and field names are indicative of function wherever possible.

#2 Code layout

Code should be well laid out and as concise as possible.

Whitespace doesn't impact code size but can make a lot of difference to readability. Blank lines can be as informative as lines full of code.

Namespace items, classes, methods, properties and field groups are separated by white space to give separation between elements so that the eye automatically distinguishes between one section and another.

Braces are on their own lines and indentation is used to indicate nesting or scope. The exception to this rule is in the case of simple accessor properties where the get and set accessors may be defined on a single line. Acessors that are more complex than assigning the value to the associated private field follow the method brace and indentation rules.

#3 Comments

Be liberal and verbose with comments and documentation. Basic Inline XML documentation is a great help when studying a class library but little or no use when trying to get into the head of the programmer, even if that programmer may have been you two years ago. Remember the remarks and examples as well as internal comments

See the code example here.

No comments: