I don’t know if someone else has already come up with this, and I’m too lazy to actually use google to look for it, but I’ve come up with a new rule for writing code.
Here’s my thesis. When describing the purpose of a class, you shouldn’t be able to use the word ‘and’.
Here’s the explanation. Any class that you write should have a very small and clearly defined purpose. For example, I was writing a class to wrap the incoming parameters of a rest endpoint. The problem was, I was trying to do too much with that one class. It was holding the pagination information, the sorting information, and the filtering information. That’s way too much for one poor class to do. It started out simple, but as I added the rest of the features from the spec, it got way too bloated. I knew, but tried to force it to work anyway.
In code review, my coworker pointed out that it was bloated, and I should refactor it out. I knew it already but didn’t want to admit. With his not so gentle push in the right direction, I spent the next three hours refactoring the code into three seperate classes. Each class was around 100 lines and served a very defined purpose. I was able to write unit tests for all three easily to verify that they worked correctly, and as a bonus, I was able to wrap my head around what they were doing much easily.
In the previous bloated object, if someone has asked me for a confidence level of how well it did it’s job across all the possible input domains to it, I’d have said somewhere around 80%. I know it did the right thing in my tests, but my tests are obviously biased. With the new design, I’d be able to say with a 99% confidence level that each piece does the right thing. That’s quite an improvement.
Another nice change with the smaller classes, was that it took me all of an hour and a half to get around 90% unit test coverage. If I’d tried writing unit tests for the heavy version of the object, I’d probably have had to write way too many tests with a lot of overlap and wasted time.
So to recap. Refactoring my object into three smaller objects resulted in cleaner more managable code. Better and faster unit test coverage. The code looked much more pleasing to the eye. Win, win, win. Ok, the last one isn’t really a win, but it is a nice side effect.
‘
Posted by Mathew Duafala