2010-05-24

C# Switch statement & enums

I wish i could write something like this:

void foo(MyEnum e)

{

  switch(e) complete

  {
    case MyOption1:

      bar(); break;

    case MyOption2:

      baz(); break;

  }

}

and expect compiler error is MyEnum also contains MyOption3. Of course, I can add

default: throw new Exception();

but this is not always appropriate when the code is not covered by automated tests. In my case, that’s how it is exactly. Some code similar to above is executed only on rare occasions, so there is little probability that the problem will be spotted by manual testing. And when it is in production, it would rather fail silently than throw unhandled exception.

Of course is is considered a bad practice to litter code with such switch statements everywhere, and bar() and baz() would better be virtual functions on polymorphic objects.

2010-05-17

Semi-Complex code

The codebase I am currently working on has some parts having as I call it, semi-complex logic. It has good names most of times, it adheres to reasonable coding standard, and it actually works. Well, most of time. However, it has copy-paste-alike constructs all around. There are lots of dead / redundant code. And each class has just too many responsibilities. This looks like a kind of code our developers seem to be happy with. Must be because they are most productive producing it. I too seem to be most productive when producing highly-entangled, low level of abstraction code. But in a few past years I settled to opinion that long-term qualities of code matter the most, event for small applications. And hence, nowadays I tend to write code I am not most productive writing, taking time to manage dependencies, eliminate duplication, extract methods. I’m still not that good at it, and of course no one appreciates it. But still I try…

What troubles me about this semi-complex code, is that it carries lots traits of bad code. Most notably, out-of-place dependencies. It suffices to have one wrong dependency, and soon inconveniences start to emerge. Like, having executable module link to seemingly unrelated one. And everyone seems to be OK with it, taking this as necessary evil. Another trouble point is that the code itself is easy to read, but it doesn’t mean you understand how it is working. Because responsibilities are not clearly separated, and some side-effects take place occasionally.