Programming style

I've been using Framework Design Guidelines for a couple of months now, and reading Brad Abrams blog for longer. It's a great book BTW. Not only does it go beyond the usual naming convention standards, it let's you know what to expect from the .net framework and how to write code that works well with it.

One of the suggestions and also one of my pet peeves has to do with returning collections. You should always return a collection even if it is empty and never return null. Null doesn't add any information to the caller and just forces them to write extra code which has no real meaning other then handling an edge case.

That's my rant for now.

Thanks

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Amen brother

That's right up there with "Don't throw exceptions for expected cases" such as, I don't know, Trying to load a business object by it's primary key, and it not being there. There's a case where throwing the exception gives you no more useful information than just returning null.

As long as that's the only reason.

What I think is worse is returning null when you should throw an exception, like when you can't connect to the database or there is a sql error. If you return null for those cases then null becomes a meaningless value, and you have drug yourself back to the world of HRESULTS.

At least developers here haven't been spooked by the exceptions are slow thing. I've worked with developers that refused to use exceptions because they read that they were slow, but thought nothing about performing a database operation once per loop.

More generally, be

More generally, be intentional about allowing a variable to be null. 

If it is meaningful for a variable to represent nothing, allow it to be null.  Generally, do not use a default (non-null) value to represent the idea of null.  (Using the null object pattern may also be exceptable in some contexts.)

Otherwise, disallow null.  Throw ArgumentNullException if an argument is null that shouldn't be.  In a language like C# that requires local variables to be initialized before they are used or returned, do NOT initialize such variables to null.  Instead, let the compiler guarantee that all possible code paths initialize the variable before it is used or returned.  Make sure you initialize it to something other than null.

Linking this to the original example, unless null and an empty collection mean 2 different things to the client, do not let the collection be null.