Reputation: 23
I'm trying to wrap my head around the SOLID principles and it seems like an interface doesn't necessarily block the creation or the use of methods not stated in the interface. Then the question is should you use the extra methods an implementation brings or strictly adhere to the interface?
I would assume not and if you needed to use said method you should create another interface / class so that you can keep the interface separation principle.
Is this right?
Upvotes: 2
Views: 115
Reputation: 575
You want to work against the interface, so then you are not able to call any other public methods.
IService service = new Service();
Of course, you can create as many public methods as you wish and create your object like this.
Service service = new MyService()
However, I don't think it's best practice.
You can implement multiple interfaces, so then let the client decide which interface is suitable to call. But you want to keep SRP in your class.
As an example below. Service
has two public methods, each defined in a separate interface. The Client
wants to work with IService
directly. A higher level will then work with IDisposable
and call Dispose()
method of that interface.
interface IService
{
void Execute();
}
class Service : IService, IDisposable
{
public void Execute() {}
public void Dispose() {}
}
class Client
{
private readonly IService _service;
public Client(IService service) => _service = service;
}
Upvotes: 3