Pattern for a class that does only one thing

Posted by Heinzi on Programmers See other posts from Programmers or by Heinzi
Published on 2012-11-08T08:34:10Z Indexed on 2012/11/08 11:21 UTC
Read the original article Hit count: 322

Let's say I have a procedure that does stuff:

void doStuff(initalParams) {
    ...
}

Now I discover that "doing stuff" is quite a compex operation. The procedure becomes large, I split it up into multiple smaller procedures and soon I realize that having some kind of state would be useful while doing stuff, so that I need to pass less parameters between the small procedures. So, I factor it out into its own class:

class StuffDoer {
    private someInternalState;

    public Start(initalParams) {
        ...
    }

    // some private helper procedures here
    ...
}

And then I call it like this:

new StuffDoer().Start(initialParams);

or like this:

new StuffDoer(initialParams).Start();

And this is what feels wrong. When using the .NET or Java API, I always never call new SomeApiClass().Start(...);, which makes me suspect that I'm doing it wrong. Sure, I could make StuffDoer's constructor private and add a static helper method:

public static DoStuff(initalParams) {
    new StuffDoer().Start(initialParams);
}

But then I'd have a class whose external interface consists of only one static method, which also feels weird.

Hence my question: Is there a well-established pattern for this type of classes that

  • have only one entry point and
  • have no "externally recognizable" state, i.e., instance state is only required during execution of that one entry point?

© Programmers or respective owner

Related posts about design-patterns

Related posts about object-oriented