Does inheritance from a class with unused methods violates the interface segregation principle?
For example:
abstract class Base
{
public void Receive(int n)
{
// . . . (some important work)
OnMsg(n.ToString());
}
protected abstract void OnMsg(string msg);
}
class Concrete : Base
{
protected override void OnMsg(string msg)
{
Console.WriteLine("Msg: " + msg);
}
}
Concrete
depends on method Base.Receive(int n)
, but it never uses it.
UPD
Definition I use:
ISP states that no client should be forced to depend on methods it does not use.
In the field of software engineering, the interface segregation principle (ISP) states that no code should be forced to depend on methods it does not use. ISP splits interfaces that are very large into smaller and more specific ones so that clients will only have to know about the methods that are of interest to them.
This principle was first defined by Robert C. Martin as: “Clients should not be forced to depend upon interfaces that they do not use“. The goal of this principle is to reduce the side effects of using larger interfaces by breaking application interfaces into smaller ones.
The Interface Segregation Principle (ISP) states that clients should not be forced to depend on methods that they do not use. Interfaces should belong to clients, not to libraries or hierarchies.
The Interface Segregation Principle states that clients should not be forced to implement interfaces they don't use.
I think you're misinterpreting what the interface segregation principle says. In your case you're fine and are not "forcing" any implementation. In fact you're applying the Template method design pattern
If you had a hypothetical
interface ICommunicateInt
{
int Receive();
void Send(int n);
}
in order to implement it, your Base
class would be forced to implement a Send
method that it does not need.
So, the ISP suggests that it is better to have:
interface ISendInt
{
void Send(int n);
}
interface IReceiveInt
{
int Receive();
}
so your classes can choose to implement one or both. Also methods in other classes that need a class that can send an Int, can require a
void Test(ISendInt snd)
// void Test(ICommunicateInt snd) // Test would "force" snd to depend on
// a method that it does not use
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With