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]

.Net C# Singleton Pattern – Best Practice

What is the best practice way to implement the Singleton design pattern in C#? You might be surprised at the number of flawed examples there are out there; many of the articles I looked at were incorrect (some subtlely, some not so) and several were on high traffic, popular sites!

This excellent article by Jon Skeet not only discusses several ways not to do it, but also the correct way:

public sealed class Singleton

{

// Prevent compiler adding a default public parameterless constructor

private Singleton() {}

public static readonly Singleton Instance = new Singleton();

// Explicit static constructor instructs compiler

// NOT to mark type as ‘beforefieldinit’

// Remove this if you do not need to guarantee lazy instantiation

static Singleton() {}

}

The static constructor is only required if you want to guarantee lazy instantiation (which Jon explains here.)

See also this MSDN article from Feb 2002.

Perth .Net UG Meeting – 10th Jan 2007

We are starting the year with an exciting talk by David Lemphers on his explorations into .NET and Robotics, 5:30pm, Weds 10th Jan 2007.

Please note that this meeting will be held at the Microsoft offices, level 14, QV1 building, NOT at the new Excom venue. Look forward to seeing you there!

He is also presenting on SQL server to the SQL UG the following evening at Excom.

Chance Quotes

Nick Randolph tagged me a while ago as part of the ‘5-things’ tagging meme pervading the ‘blogosphere’. Try as I might, I couldn’t find 5 things about me that I thought others would be interested in knowing (sad, I know), so instead here’s a few quotes and food for thought from interesting people about chance:

Chance favours the prepared mind – Louis Pasteur.

I will study and get ready, and perhaps my chance will comeAbraham Lincoln

God does not play dice [with the universe] – Albert Einstein

Men are not prisoners of fate, but only prisoners of their own mindsFranklin D. Roosevelt

Fortune can, for her pleasure, fools advance, And toss them on the wheels of ChanceJuvenal (55 AD – 127 AD)

No victor believes in chanceFriedrich Nietzsche

A lie gets halfway around the world before the truth has a chance to get its pants onWinston Churchill

When a man is pushed, tormented, defeated, he has a chance to learn somethingRalph Waldo Emerson

Fortune knocks but once, but misfortune has much more patience – Laurence Peter

Great lives are the culmination of great thoughts followed by great actions – Peter Sinclair

Chance is always powerful. Let your hook be always cast; in the pool where you least expect it, there will be a fishOvid (43 BC – 17 AD)

The Churchill quote is a bit of an odd one out.

I think I can see my parcel!

Huh?

Having had a few xmas parcels go astray en route from Australia to the UK (not to mention the horrendous cost of postage), a colleague suggested that I simply buy a few things from Amazon UK. Brilliant! Now why didn’t I think of that! Worked so well, I sent two shipments. I came across this image today, and wanted to share it: Amazon UK at xmas! If only software could be written that way…

Microsoft up to its old Tricks?

Just when I was starting to be a Microsoft champion and truly believe they had turned over a new leaf, they go and do something like this: Microsoft tries to claim a patent on RSS (just a few days ago). This is ridiculous and disgraceful! Everyone knows that Microsoft did NOT invent RSS! In fact, they were relatively slow to adopt support for RSS into their products. MS, you need to get those patent guys under control, before they seriously start damaging your newfound credibilty.

What Developers Want

Rob Walling has posted an article, Nine Things Developers Want More Than Money, that managers should read, if they want to understand what makes most developers tick. Rob draws upon Frederick Herzberg’s Two Factor Theory.

Just over 1 year ago I left a job at an engineering company in Perth (with its head office in Canada). In the space of just 10 months, before and after I left, my department had a turn over of its entire complement of staff. I mention this, because all of the problems and complaints voiced by the developers are discussed in this post. [This one’s for you Bernie!] On the positive side, everyone that left found better jobs.

Over to You!

With the New Year quickly approaching, it’s not unusual to find people thinking about changing positions or jobs and with that in mind Rob Farley has posted an intelligent and insightful piece of the subject of handing over one’s responsibilities at the end of an employment.

I really like Rob’s suggestion that a handover be ‘practised’. It’s a bit like factoring in ‘mock’ database backup restores into an overall risk strategy plan (I have witnessed first hand, 2 large engineering companies being caught short, by not checking that there was actually something on those backup tapes, that they were sending offsite to a fire safe for 2 years!)

Bloated, Forgettable Software Dripping with Mediocrity!

OK, hopefully that title got your attention! More about it later…

I’m starting to realise that a technique I’ve successfully used to build applications in the past is closer to Test Driven Development than I had imagined. Namely creating paper based screen mockups, acting these through putting yourself in place of the user, and then building live prototypes. Let me begin at the beginning…

Last week I purchased an e-book from 37Signals, “Getting Real: the smarter, faster, easier way to build a successful web application”. It cost US19 (approx. AUS25) and was well worth the money. But check this out; you can even read it for free here! Free! How cool is that?

It says ‘web’ in the title, but it is equally applicable to non-web based software. The idea is to minimise non-executable artifacts (i.e. not actually running in the application), such as doco, diagrams etc…This is very similar to the theme that runs through agile development.

  • It’s about staying small (and agile).
  • It’s about less of everything that’s not essential.
  • You start with the interface, the actual screens that users will interact with.
  • It’s about short iterations (just like agile), and reducing the cost of change.
  • And more specifically, it’s about delivering just what customers need (just like agile).

Just like TDD, we deliver better results because we are forced to think about the actual problems we are trying to solve, rather than our ideas about how they should be solved.

[I did a short stint at a home loan company where they did things the opposite way: create a load of throw away, static mock up screens rather than real pages, and produce documentation that is out of date the minute you publish it. But I digress…]

I was amused to see a quote from the Elements of Style, on vigorous writing, as I blogged about the similarities in the process of software development and ‘good’ writing a while ago here.

One description that really stuck in my mind was: bloated, forgettable software dripping with mediocrity. Gotta love that for a put down!

OK, so we come to the central tenet of this eBook: you don’t need tons of money or a huge team or a lengthy development cycle to build great software. Less software, less code, less mass. More simplicity for your users. More user buy-in and more users who are passionate about your product.

Here is some of the condensed ‘Getting Real’ advice:

Use a team of three for Version 1.0
Start with a developer, a designer and someone who straddles both worlds. Starting with a small team will force you to make trade-off decisions early in the development process. Such a small team will communicate more effectively and efficiently than a larger one.

Let limitations be your guide to creative solutions
You are never going to have enough of all the things you would like; be it time, money, people etc. Don’t worry! Constraints are great for driving innovation and putting the brakes on ‘feature creep’

What does your application stand for?
What makes it different than other similar products? Why is there a need for it? Before you even think about coding you need to know the purpose of the product you are going to build – the vision.

Ignore details early on
Always work from large to small. Let the details reveal themselves as you use what you are building.

“Getting Real” continues for a good 130 pages more than I’ve briefly skimmed over here. It’s worth a read.