You wouldn’t know good code if it punched you in the face

Why?  Because, usually good code doesn’t punch you at all.

In fact, some of the best code examples I have ever seen I use everyday… and it’s not mine.  It’s the sort of stuff that with only a few seconds of investigation you can assert what needs to be done and why.  The names make sense, the flow is smooth, the functionality is discoverable.  Where is this marvelous code? It’s in the .NET framework.

Sure it does some things wrong and sure we could argue the technical merits of some decisions MS makes… but that isn’t really the point is it?  Did you know what they have usability tests on the framework in order to help YOU take advantage of their API?  Who else is doing that?  My guess, not very many others.

Here is an example to ponder:

a)

DateTime.Now.AddDays(2).Day;

b)

DateTime currentDate = DateTime.Now;
TimeSpan days = new TimeSpan(2,0,0,0);
DateTime futureDate = now.Add(days);

While both are equally valid (and do the same thing), the first option is far more direct and easy to use than the latter.  Had I not used relatively good naming on option B, for someone unfamiliar with the TimeSpan class there would be no way to know what the 2 stood for.  In fact, there is still no guarantee that the 2 means 2 days at all.  It’s implied by the name of the method, but I might have it wrong.

Eric Evans and Martin Fowler would call option A) a Fluent Interface.  That is, by chaning a series of methods together (and some other stuff), the resulting code is more natural than if you were take another path.

Very cool stuff, I recommend taking some time to learn how to add this to your toolbox.  Other developers will thank you some day.

Advertisements
Post a comment or leave a trackback: Trackback URL.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: