Thursday, January 30, 2014

Introduction of the series

Writing code is an exciting business. At least it always been like that to me. It is fast and ever-changing business.

Every day talented people strive toward making software faster, more stable, more secure. And at the same time, even more talented people are looking for ways to break it :-)

Hardware manufactures come up with new components that open up possibilities that were unimaginable just a several years ago. And at the same time these advances make certain ‘industry standard’ patterns and practices dangerous and obsolete.

Keeping up with technology is very important for any kind of engineer, but for The Software Engineer it is an absolute necessity.

Every one of us have a favorite way of doing things and but time to time we have to re-evaluate our coding habits.

In this (hopefully) weekly blog I’m going to illustrate patterns, practices, code snippets that I find interesting, dangerous, cool, exciting ,etc.

Just to illustrate my point, I’m going to give you a simple example. I’m pretty sure that every one of you ​already knows about this coding pattern and never ever write code like that. You don’t, don’t you? ;-)

So, 11 years ago, in .NET 1.1, this snippet was perfectly fine:

but later, someone decided to upgrade to .NET 2.0 and use modern Dictionary object in initialization. This code still works, as expected:
 
But sometime later, when new developer decided to use modern initialization pattern and made a small change to the code, just replaced IDictionary with var: then BOOM, code no longer works:
 
The reason code used to work before and not anymore is that implementation of the Dictionary class is backward compatible, when casted into IDictionary interface, but when it is used directly, this class produced an exception, as it supposed to do.

But let's say that you are not aware of this change, and you keep writing code that relies on dictionary to return null, when key is not found. Yes, of cause if you have a solid set of unit tests to cover every line of your code and every possible combination, then you’ll see this problem right away. But we all know that unfortunately it is not a reality and code like that can sneak into production.

So the new, modern code should probably look like this:
 
As I said, this example is trivial, but nevertheless important to remember.

No comments:

Post a Comment