I’m working on a project right now, and I need to fetch a particular object from the database. Unfortunately, the method I need doesn’t exactly exist, despite the fact that the object is stored in the database and has a strongly-typed class that defines it.

I have to sit here and figure out exactly how to use the existing code to fetch the object I need and use it the way I want. Realistically, I’m going to have to either a) modify the existing code to make it generic enough to satisfy its existing purpose as well as my own, or b) write new code to fetch the object in the way I need it.

The fact that I’m facing this decision is exactly the kind of scenario that leads to code sprawl. In fact, I’m sure that this has already happened in our current code base, for this exact reason. I see stored procedures and methods all over the place that perform similarĀ  — but not identical — retrievals of the same information.

So, how do you get out of this pattern?

Well, the answer is pretty straightforward: when you realize you’re about to write code that does something very similar to another piece of code, find a way to combine those functions into a single unit of code. Of course, this is downright scary to do if your code isn’t well-covered by tests. You know, because Murphy’s Law.

But, if you want your codebase to improve and be easier to work with, then it’s worth finding the time to make these kinds of changes. Furthermore, it’s best to make those changes right when you find the issue, because the same reason the earlier developer didn’t make the code generic enough at the outset is the same reason you won’t come back and do it later: you won’t have enough time or clarity to do it in the future.

Over time, these small changes improve the codebase and make it easier to work with, thereby improving the team’s productivity. It just takes a little bravery — and a little brevity — to accomplish it.