Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance and Interface segregation principle

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.

like image 851
astef Avatar asked Jul 10 '13 07:07

astef


People also ask

What is meant by Interface Segregation Principle?

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.

What is the benefit of the Interface Segregation Principle?

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.

What is Interface Segregation Principle in relation to application development?

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.

What is Interface Segregation Principle in Swift?

The Interface Segregation Principle states that clients should not be forced to implement interfaces they don't use.


1 Answers

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 
like image 188
Paolo Falabella Avatar answered Sep 23 '22 20:09

Paolo Falabella