Reuse vs. Use Once
Thursday, August 7th, 2008Brent Simmons just put a post up on his design philosophy for category methods, in which he presents the following rule:
If something is used just once, don’t make a category for it, just make it a static C function. Unless it’s big.
His reasoning is as follows:
- Less code to maintain. (And, in this case, two fewer files: one deleted .h and one deleted .m.)
- The code appears where it’s used: no need to jump to it if I need to edit it.
I’ve had this rule for a while, as well, and I think it’s a good one. But I have a third reason for employing it: if you’re only using a method in once place, you have no idea how it’s going to generalize. Maybe you can reuse it, as-is, in many other places. Perhaps it will need to be decomposed.
But trying to figure this stuff out the first time you need the functionality is a waste of time, because you’re likely to guess wrong. It’s better to save your energy for when you don’t have to guess at all: the second time (or the third time, or the fourth time) that the problem shows up, when you can refactor your way to a truly general solution.