If you have a utility class in your current code base, there’s something very important you should do - even before you apply any of the techniques we’ve discussed previously.

You should stop making the problem worse.

Next time you write a new method and you’re tempted to add it to your existing utility class so that it’s reusable, stop. If you’ve started making the change to the utility class, take a copy of your changes and then revert the file.

Just don’t do it.

Think about the method you’re adding and what it does.

  • If it’s very specific to your current case, admit that reuse is very unlikely (this can be difficult to do!) and make it a private method somewhere close to where it is used.
  • If it’s a useful addition to a class that you don’t control, add it to a static class of extension methods. Create the extension class if it doesn’t already exist.
  • If it’s a useful addition to a class that you do control - or that you’re allowed to change - then add the method to that class. Do some refactoring to keep things tidy, and add some unit tests if that’s appropriate.
  • If it could be combined with other methods to make a useful semantic type, consider creating that type and using it to solve your current problem. You don’t need to push the use of that semantic type across the entire codebase in one go.

At its core, the advice is very simple: the first step when fixing a mistake is to stop making the mistake.

About this series

Cleaning up the dumping ground of the utility class.

Posts in this series

Using Extension Methods
Using Semantic Types
Using Consolidation
With Relocation
Using Premeditation
Prior post in this series:
With Relocation

Comments

blog comments powered by Disqus