What are the benefits of using a concept such as IStartable?

Instead of using this interface:

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

Usually I just make the constructor of the object run the Start () code and implement IDisposable so that the dispose method executes the Stop () code.

Is this just a matter of style? Or did I miss something important without having something like IStartable? All I see is additional complexity because you have to maintain its start / stop state.

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

EDIT: Great answers, you convinced me to use the interface for startup objects. I can’t decide which answer is better, so I agree with the one who has the most votes in 24 hours.

+3
source share
3 answers

The common advantage of using an interface is self-description and self-promotion. If there is no interface, you have no way to ask the object, "can you start and stop?" If you use the interface, on the contrary, you can request objects to see which of them will respond to such messages. Then you can be safely guaranteed that such objects implement the functionality encapsulated by the interface.

+6
source

in general, constructors must create a properly initialized object

and nothing more!

+4
source

, , , "" (). , , ( / !) SoC.

It also leaves a lot of ambiguity. For the consumer, for a given object, how do we know that it "starts" when we call ctor? "For a given object that does not conclude a contract, should I leave it in the hope of the author that it meets my expectations?" The interface makes the presence and availability of the action explicit.

+2
source

Source: https://habr.com/ru/post/1709055/


All Articles