Question

Instead of using an interface like this:

public interface IStartable
{
    void Start();
    void Stop();
}

I usually just make the constructor of an object run the Start() code, and implement IDisposable so that the dispose method runs the Stop() code.

Is it just a matter of style? Or am I missing something important by not having something like IStartable? All I see is extra complexity, because you have to maintain it's started/stopped state.

What are the pros and cons of using start/stop vs using ctor/dispose, especially in the context of an IoC/DI container?

EDIT: Great answers, you've convinced me to use an interface for startable objects. I can't decide who's answer is the best so I'll accept whoever has the most up votes after 24 hours.

Was it helpful?

Solution

The general advantage to using an interface is that they're self-describing and self-advertising. If there's no interface, you don't have a way to ask an object, "can you be started and stopped?" If you do use an interface, by contrast, you can query objects to see which of them will respond to those kinds of messages. Then you can be safely guaranteed that such objects have implemented the functionality encapsulated by the interface.

OTHER TIPS

in general, constructors should produce a properly-initialized object

and nothing more!

It could possibly depend on what, specifically, you mean to be happening when you say Start(). But in general, mixing object initialization with routine execution (especially stateful and/or long-running execution!) violates SoC.

It also leaves a great deal of ambiguity. To a consumer, for a given object how do we know it is "starting" when we invoke the ctor? "For this given object, which implements no contract, I must leave it to hope in the author that it conforms to my expectations"? An interface makes the presence and availability of the action explicit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top