Name of (anti?)pattern: helper class to implement free function

  softwareengineering

Suppose we have a publicly declared function

Result ComputeResult(Foo foo);

whose implementation is complex and requires some temporary data structures. I might break the implementation down into steps to improve comprehension:

Result ComputeResult(Foo foo) {
  Result result;
  std::map<Bar, Baz> bar_to_baz;
  std::vector<Baz> extra_bazzes;
  GroupByBar(foo, &bar_to_baz, &extra_bazzes);
  AppendExtraBazzes(extra_bazzes, &bar_to_baz);
  ModifyBazzes(&bar_to_baz);
  // etc
  PopulateResult(bar_to_baz, &result);
  return result;
}

Passing the temporary structures around can get cumbersome, especially if the calls are nested; a parameter may only be indirectly relevant to the top level call. In some cases I find it more readable to define a helper class to hold them, instantiated once per function invocation:

class ResultComputer {
 public:
  ResultComputer(Foo foo) : foo_(foo) {}
  Result Compute() {
    GroupByBar();
    AppendExtraBazzes();
    ModifyBazzes();
    // etc
    PopulateResult();
    return result_;
  }
 private:
  void GroupByBar();
  void AppendExtraBazzes();
  void ModifyBazzes();
  void PopulateResult();

  Foo foo_;
  Result result_;
  std::map<Bar, Baz> bar_to_baz_;
  std::vector<Baz> extra_bazzes_;
};

Result ComputeResult(Foo foo) {
  return ResultComputer(foo).Compute();
}

I vaguely recall some advice about this but can’t find it – I don’t know what to search for. Does this pattern have a name?


Note: I’m not asking about the value of the pattern; that’s a separate question. I’m certainly not asking for detailed comments on my (very contrived) example.

8

Parameter Object gives a name to refactoring, that groups multiple method arguments and helps with their propagation.

I never call them as such though.

1

LEAVE A COMMENT