Coding Standards

Recently, I needed to define some coding standards that I think are important.  I thought it would be good to list them in a post.  My opinion has been impressed on over the years by the writings of “Uncle Bob”, Martin Fowler and Steve McConnell in their books and articles such as: Clean Code, Refactoring and Code Complete.  Another interesting publication is Microsoft’s Framework Design Guidelines.  There are many others that I have read and I highly recommend that all developers strive to write code that is easy to read and maintain.

Here is my short list:

1. Avoid Flag Arguments
They complicate the method signature:

They add complexity to the API internals. They don’t communicate their intention well, making them harder to use.

2. Prefer Polymorphism to If/Else or Switch/Case

3. Avoid nullable types or at least minimize their visibility

They add complexity to code, especially in API signatures. They require more validation checks.

Only use if it adds value.

Don’t use nullable Boolean values. If you need 3 states then use an enum instead

4. Avoid Negative Conditionals

5. Avoid putting database dependencies into business logic APIs

That is the API shouldn’t call the database but instead the calling API should pass the data in

6. Prefer guard clauses instead of nested if/else return statements

7. Prefer few method parameters

8. Prefer smaller methods and smaller classes

9. Limit Exception Handling.

The point is that you don’t have to catch exceptions at every method but can let them bubble up to the top method. When logging, log in the business layer and catch and log in the method at the top of the call. In general, that should be the practice. There are exceptions such as detail logging in jobs and also where you don’t want the program flow to be aborted.

10. Clean up code as you make changesFormat code. Visual Studio has shortcuts to format code:

Ctrl-k/Ctrl-d – formats code on open file

Ctrl-k/Ctrl-f – formats selected code

11. Remove unused, unreferenced and commented code.

12. Single Lager of Abstraction principle

One issue I see all the time is hard to read logic.  That tends to be fragile and lead to bugs.  Polymorphism help with that.  Also we can develop smaller APIs with the logic so that the main code reads better and the logic is isolated and can be thought of and as a unit.  I believe the concept that I’m describing is the Single Layer of Abstraction principle (SLAP).  “Uncle Bob” and Kent Beck discuss this in detail in their writings.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s