Tuesday, October 14, 2014

Single Repository Principle

SRP

Single Repository Principle which is also known as Single Repository Pattern or in short SRP says a class should have one and only one reason to change.

Wikipedia says In object-oriented programming, the single responsibility principle states that every context (class, function, variable, etc.) should have a single responsibility, and that responsibility should be entirely encapsulated by the context. All its services should be narrowly aligned with that responsibility.
To explain this further let’s assume we have a class to export dataset into excel and pdf.

    public class ExportDataGrid
    {
        public DataSet ds { get; set; }
        
        public void ExportToPDF()
        {
            // code for export to pdf
        }

        public void ExportToExcel()
        {
            // code for export to excel
        }
    }



The class ExportDataSet has two methods, ExportToPDF and ExportToExcel. Now think we want to add a new functionality in ExportToPDF method. We will change this method . And if we need to change something in ExportToExcel method then also ExportDataSet class got modified. So it has two reason to change the class. Here SRP come into picture. For removing this dependency we just split this class.

    public interface IExportDataGrid
    {
        void Export();
    }

    public class ExportToPDF: IExportDataGrid
    {

        public void Export()
        {
            // code for export to pdf
        }
    }
    public class ExportToExcel : IExportDataGrid
    {

        public void Export()
        {
            // code for export to excel
        }
    }



This is what SRP is all about. Happy Codding...