0

I'm trying to define interfaces for services that should have methods like start, stop, Resume.

But some services can be asynchronous which needs to implement the same methods (start, stop and Resume) asynchronously. One more caveat here is asynchronous method also accepts cancellationToken

Problem Some services can start async and stop synch. By following ISP(Interface segregation principle). if we create a consumable interface i.e

public interface IStartable 
{
        void Start();
}

public interface IStopable
{
        void Stop();
}


public interface IStartableAsync
{
     Task StartAsync(CancellationToken cancel);
}

public interface IStopableAsync
{
   Task StopAsync();
}

public interface IStartStoppable: IStartable, IStopable
{}

public interface IStartStoppableAsync: IStartableAsync, IStopableAsync
{}

As we can see above, it needs to create too many interfaces with various combinations.

Is there any better way of designing this, which is relatively simple and maintainable?

prasana kannan
  • 646
  • 6
  • 12
  • 1
    If you need to support `async`, define your interface methods to return a `Task`. If any need to be implemented synchronously, you can use `Task.CompletedTask`. – Johnathan Barclay Sep 14 '21 at 15:14
  • 2
    `IStartStoppableAsync` doesn't seem to be using the correct interfaces. – LarsTech Sep 14 '21 at 15:14
  • Seems like those interface are just markers - at least the last two ones. Why do you even have them in the first place? Let a class just implement `IStartable` and `IStoppableAsync` instead of `IStartSyncStopAsync`. – MakePeaceGreatAgain Sep 14 '21 at 15:18
  • @HimBromBeere Because you can't have a field that is "both IStartable and IStoppableAsync", but you *can* have a field that is `IStartSyncStopAsync`. – Servy Sep 14 '21 at 15:44
  • @JohnathanBarclay Then you're lying in your API about what you provide. Claiming you support asynchronous operations *and then performing them synchronously anyway* means that a method someone is expecting to return quickly is going to not, and that's quite likely to be problematic. – Servy Sep 14 '21 at 15:47
  • @JohnathanBarclay we could do that but, we would force the service to implement the method which it doesn't want to implement (i.e sync service needs not implement async start method). which violate the interface segregation principle – prasana kannan Sep 14 '21 at 16:16
  • @LarsTechLarr I've updated properly now – prasana kannan Sep 14 '21 at 16:18
  • @RyanWilson As mentioned above, it will violate interface segregation principle – prasana kannan Sep 14 '21 at 16:19

0 Answers0