This is the Demystify SOLID article series. In this series we will be talking about SOLID principals of software architecture, if are very interesteded in learning good practices and design then you are in the right place.
In our previous article we have discussed the “Single responsibility principal”. If you are new to this series then you can read it here.
Demystify SOLID: "S" For Single Responsibility Principal
Demystify SOLOD: "S" for Single responsibility principal
As per the title, we will understand the concept of “Open close principal in this article”. It's another good principal of application development. The open close principal suggests that “One class (or software component) will be always open for extension and closed for modification”. Let's discuss that a little.
public class employeeProcess
{
public string employeeName { get; set; }
public void PrintEmployeeType(int type)
{
if (type == 1)
Console.WriteLine("Permanent Employee");
else if (type == 2)
Console.WriteLine("Temporary Employee");
}
}
We have designed the “employeeProcess” class that will happily print an employee type using the “PrintEmployeetype()” function. The logic is pretty simple, we are checking the input type of the function. If the type is 1 then it will print Permanent Employee and if the type is 2 then it will print Temporary employee.
Fine, and simple. But here is one limitation in this definition. If the organization then adds one more type of employee in the organization like “contractual employee” then they need to modify the exhisting employeeProcess class. Is that inconsistent with the “Open close principal”? Because we know that the component will be opened for extension but closed for modification but we are trying to modify the existing class. So, what is the solution? It's simple, when it is ndecessary to add new functionality to an existing class, just extend the class rather than modify it. Here is the modified implementation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Collections.ObjectModel;
namespace FuncTest
{
public class employee
{


Jasminder SinghPosted Apr 25, 2014, 11:36 AM
I am not sure but i think, you need to modify your example a bit. You have provided the right example of which can be modified according to SRP. But you have completely removed the class employeeProcess, which required you to implement this principal. So this is an implementation of loose coupling using the interfaces. To be more precise, you could have kept the class employeeProcess and passed the interface based instance of PermanentEmployee or ContuctBasedEmployee to the PrintEmployeeType method of the employeeProcess class. Let me know if, I am missing something here.