Tuesday, June 8, 2010

Inversion of Control - Results

In a previous post I talked about how to identify and re-factor a section of code that had a switch statement in it.  I was finally able to get to that statement at work and re-factor it.  I thought the results would be interesting to post.

First and foremost, I was able to remove 120 unnecessary lines of code and replace it with 2 lines.  That's right, where once there were 120 lines there are now  2.

But there is more to the story than that.  As I mention before, I've been unit testing the application(and that led to a new Eclipse tool), so as I re-factored the system, I re-ran my tests.  At one point my tests FAILED.  That's right, I BROKE the intended functionality with a re-factor that shouldn't have.

When I looked into it further, I found that one little switch statement buried in that twenty-two case wonder didn't follow the pattern.  Instead of getting an implementation from the factory and calling a getMap method, it was calling an entirely different method in the main class.  After a little research and a few short lines of code, the issue was fixed and the tests once again showed a green bar.

The actual work here is not relevant, what is relevant is this:  This is a pre-release version of this system.  It is not even in Beta testing yet, and there is already a place in the code that was 'hacked' to work differently than you would expect.  The implementation of a pattern will help prevent this kind of degrading of the code in the future, but it was there.  In the code. Before the software was even released.

The second thing to take away from this:  If I hadn't written all those unit tests, I wouldn't have found the error.  I would have re-factored the code and introduced a bug into the system without realizing it.  Unit tests saved me.  And because of that, my company will now have a system that is more resistant to errors and less prone to new bugs.

1 comment:

  1. From this post I envision you as a cyber cowboy, urging your pony through the dense undergrowth of code and fanning your pistol with lightning-quick hands to kill bad error Indians just as they're about to raid a tiny settlement of weary women and children below.

    ReplyDelete