Tuesday, January 09, 2007

 

A Little Gem of a Book: “The Elements of C# Style”

Here is some condensed wisdom for C# programmers from a ‘must read’ book, The Elements of C# Style. This book models itself in the tradition of “The Elements of Style”, and is a similar physical size, which means you can easily read it cover to cover in very little time.



If you program in C#, having a copy of this book on hand will provide a great reference, at least until you commit it all to memory! Some of this sage advice applies to other languages as well:

  • Use meaningful names. Names things accurately and consistently
    With the exception of loop variables used as a counter or index within a loop (where using ‘i’ is often more readable than a longer name).
  • Use names that exist in the terminology of the target domain
  • Do not use excessively long names or excessively short names
  • Do not shorten names by removing vowels; use complete words
    It’s not the 1970’s! Your compiler is not going to complain about names longer than 32 chars (Oracle might though!) Take this along with the previous suggestion.
  • Avoid abbreviations unless the full name is excessively long
  • If you really have to use an abbreviation, use one that is widely used and commonly accepted.
  • Pluralise the names of collections
    List cars = new List();
    Car car = cars[index];

  • Prefix interface names with “I”
  • Use nouns to name interfaces that describe service declarations
    public interface IMessageSink
    {
    public void MessageReceived();
    }
  • Use adjectives to name interfaces that describe behaviours
    Most of these will end in –ible or –able.
    public interface IDriveable
    {
    public void Drive();
    }
  • Add a suffix of “Base” to abstract base types
  • Add a suffix of “Exception” to custom exception types

I did find a couple of typographic errors and one bit of advice which is considered wrong if you go with the recommendations in the Framework Design Guidelines by Brad Abrams and Krzysztof Cwalina; namely, point #157 states that you should derive custom exceptions from ApplicationException. These should be derived instead from System.Exception.

Also, quite by coincidence, on a second re-read I noticed that the double-lock pattern used in point #85, should not be used (see my previous blog post which refers to Jon Skeet’s article). Jon mentions that it can be fixed using memory barriers via the volatile keyword, which in this particular example would require the instance of LoanCalculator to be declared as volatile. But, he also mentions that the experts can’t agree on this, and is therefore sensibly avoided!

I believe point #48 should read:
[MyFavouriteAttribute]



    

Powered by Blogger