Interface segregation Principal (ISP)

ISP States that no client should be forced to depend on methods it does not use. ISP is one of the five SOLID principles of Object-Oriented Design.

The below example i have create Imamals interface for Mamal features. Interface is having two features like canfeed, canSpeek . But CanSpeek in only applicable for Human . It is not required for Tiger Object. 

/// <summary>
    /// Mamal Features implemneted for Human
    /// </summary>
    public class Human : IMamals
    {
        public void CanFeed()
        {
            Console.WriteLine("Human Can Feed..");
        }
 
        public void CanSpeek()
        {
            Console.WriteLine("Human Can Speek..");
        }
    }
    /// <summary>
    /// Mamal Features implemneted for Tiger
    /// </summary>
    public class Tiger : IMamals
    {
        public void CanFeed()
        {
            Console.WriteLine("Tiger Can Feed..");
        }
 
        public void CanSpeek()
        {
            throw new NotImplementedException();
        }
    }
 
Human human = new Human();
            human.CanFeed();
            human.CanSpeek();
 
            Tiger tiger = new Tiger();
            tiger.CanFeed();
     tiger.CanSpeek();
ISP Implementation
 
We have already know the CanSpeek implementation in the ABOVE example. Here we split the Interface in two, one is for Common and another for Specific.
/// <summary>
    /// Interface For common
    /// </summary>
    public interface IMamalsCommon
    {
        void CanFeed();
      
    }
    /// <summary>
    /// Interface for Specific
    /// </summary>
    public interface IMamalsSpecific
    {
        void CanSpeek();
    }
 
 
    /// <summary>
    /// Mamal Features implemneted for Human
    /// </summary>
    public class Human : IMamalsCommon,IMamalsSpecific
    {
        public void CanFeed()
        {
            Console.WriteLine("Human Can Feed..");
        }
 
        public void CanSpeek()
        {
            Console.WriteLine("Human Can Speek..");
        }
    }
    /// <summary>
    /// Mamal Features implemneted for Tiger
    /// </summary>
    public class Tiger : IMamalsCommon
    {
        public void CanFeed()
        {
            Console.WriteLine("Tiger Can Feed..");
        }
 
    }
.
Human human = new Human();
            human.CanFeed();
            human.CanSpeek();
 
            Tiger tiger = new Tiger();
            tiger.CanFeed();
 
When an interface is implemented for a wide responsibility of members then there will be chance where some clients may have to implement members, which they don’t even use.

 

2 comments:

  1. IMamalsCommon interface doesn't have CanSpeek() method implementation right? As per your code, it is available ;)

    ReplyDelete
  2. Thanks AnuRaj ...

    I have modified the Implementation

    ReplyDelete