Separate Class vs Method


Quick design question.

ClassA has a method called DoSomething(args)

In DoSomething(), before it can actually do something, it needs to do some preparatory work with args. I believe this should be encapsulated within ClassA, (as opposed to doing the prep work outside and passing it in) as nothing else needs to know that this prep work is required to DoSomething.

However, it's where the actual preparatory work code belongs that is making me think.

The preparatory work in my particular example is to create a list of items, which satisfy a certain condition, from args.

My hunch is that I should create a new class, ListOfStuff, which takes args in its constructor and put this preparatory work here.

From a TDD-perspective, I think this is the right choice. We can then unit test ListOfStuff til our heart is content. If we had put the preparatory work in a private method of ClassA, we'd have only been able to indirectly test it through testing DoSomething().

But is this overkill? Since adopting the TDD and DI approach, I've seen the number of classes that I write multiply – should I be worried?


Best Solution

There are a couple of heuristics here.

  1. Is there state on this class that survives from invocation to invocation? Does this prep work get done every time you need to doSomething(), or is it done and saved? If so, that argues for the class.
  2. Does this computation need to happen in more than once place? If so, that argues for a class.
  3. Can the details of the implementation of the doSomething() method, or the preparation work for it, change without affecting the enclosing class? If so, that argues for a class.

Well, three heuristics. No one expects the Spanish Inquisition.