Every decent programming book tells you to write readable code. Few people do.
Code is read a lot more often than it is being written. Fact.
Programming style is all about personal taste. Agreed.
On the other hand, well... let's just take a very small piece of code from the BCL written by Microsoft:
Type p = this;
if (p == c)
return false;
while (p != null) {
if (p == c)
return true;
p = p.BaseType;
}
return false;
Without changing any of the code (except spacing and indentation):
Type p = this;
if (p == c)
return false;
while (p != null)
{
if (p == c)
return true;
p = p.BaseType;
}
return false;
I know the code is longer, and there are better examples to be found, but what makes code readable is being able to see the structure of the source code. This can be accomplished by using correct spacing, empty lines and correct placement of braces.
I especially want to stress the importance of using empty lines. Their primary purpose is to visually separate blocks of code. Note the example above. The original code has no empty lines whatsoever, which makes code very hard to read (even if you wrote the code yourself).
When should you use empty lines (IMHO) :
- Before and after every control block ("if", "for", "while")
- Before and after return statements
- After blocks of variable declarations
- After blocks of assignments
- In between assignments if they "don't belong together"
- (a curly brace counts as an empty line of course)
This is a small code fragment which illustrates some of these points:
newSetMethod = typeBuilder.DefineMethod( /*ommitted*/ );
ILGenerator ilGen = newSetMethod.GetILGenerator();
ilGen.Emit(OpCodes.Ldarg_0);
ilGen.Emit(OpCodes.Ldstr , baseProperty.Name);
ilGen.Emit(OpCodes.Ldarg_1);
if (baseProperty.PropertyType.IsValueType)
{
ilGen.Emit(OpCodes.Box,baseProperty.PropertyType);
}
ilGen.EmitCall(OpCodes.Call,setFieldMethod,null);
ilGen.Emit(OpCodes.Ret);
Of course, there's more to readability than inserting empty lines, but it's a point which is often neglected. The most often heard excuse is that it makes code shorter. (sigh)
I don't want to start a religious war, just trying to express a (strong) opinion.

•