Wednesday, August 2, 2017

SOLID Principles - Interface Segregation Principle

"many client-specific interfaces are better than one general-purpose interface." 

No clients should be forced to implement methods which it does not use and the contracts should be broken down to thin ones

Here is the example to explain the Interface Segregation Principle


Here is an ISystem general purpose interface to perform more than one tasks like print, fax, scan and photocopy.

   interface ISystem

    {

         bool print(Item item);      

         bool fax(Item item);

         bool scan(Item item);

         bool photoCopy(Item item);


    }

but in real world, one system can do only few task example scanner machine can do only scanning similar like Fax machine can do fax only so we need the very granular level of interface for each system.

Here are an example:

For Fax Machine


  interface IFax

    {

         bool Fax(Item Items);

    }


    class FaxMachine : IFax

    {

        public bool Fax(Item Items)

        {

          // Send Fax

        }

    }

  

 For Scanner Machine


 interface IScan

    {

         bool Scan(Item Items);

    }


    class Scanner : IScan

    {

        public bool Scan(Item Items)

        {

            // Scan Letter

        }

    }



In real world, possible one machine can do more than one task, in this scenario we can use inherits more than one interface


interface IXMachine : IScanIFax

    {


    }


    class XMachine : IXMachine

    {

        public bool Fax(Item Items)

        {

            // Send Fax

        }


        public bool Scan(Item Items)

        {

            // Scan Letter

        }

    }


In above code, we have an XMachine which is capable to perform Fax task and also scan task.


Benefits of Interface Segregation Principle:

  • More granular and more specific interface intended to keep a system decoupled and thus easier to refactor, change, and redeploy.
  • Interface should be so smaller and more specific ones so that clients will only have to know about the methods that are of interest to them.  

Other SOLID Principles related Links:







Thanks for Visiting!!

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...