Open / Closed Principle (OCP)
If you are following the Software Design Principles while developing an application, the first thing that comes to your mind is the Open Close Principle. In Open Close Principle, it is stated that Software entities should be open for extension but closed for modification.
"Open for extension, closed for modification"
Let us put this in other words. Let us think how you can make changes to the behavior of an object without modifying it ? Well, the answer is to place the change in behavior in its derived classes or rather by creating another class and overriding their functions. A class that violates this principle would require you to have bloated class. Each time you have to add something, you need to add it to the original class.
Let us take an example :
class User
{
public bool IsAdmin {get;set;}
public void GetProperties(bool isAdmin) { ... }
}
Let us take an example of the above class. Here there is a property inside the class which states that the user is admin or not. This is a bad design. Say, there is a requirement to add another level of user called SuperAdmin. In that case, you need to change the class User again and add the IsSuperAdmin property. Rather than going with this design, we will need to use Inheritance.
public class User
{
public virtual void GetProperties() { ... }
}
public class AdminUser : User
{
public bool IsAdmin { get { return true;} }
public overrides void GetProperties() { ... }
}
Thus when there is a new requirement, the GetProperties can be easily overridden in another type of user.