This is not about Open-Close Principle(OCP), this is all about Interface Segregation Principle(ISP) in SOLID.
ISP stands for your new function should not effect your existing code which does not need this function. Simply, there is A
class code and do not disturb it by adding new function if it doesn't need.
Assume that there are Log
and Customer
class. Log
class does not need to Delete
function but Customer
does. In this case, if you add Delete
function to IRepository<T>
, you violate ISP because Log
class does not need this function and you force to add this redundant function for it.
If you need IRepository<T>
having all functions, then reconsider Log
class should implement this interface or another(s).
OCP stands for creating your code without needing(close) to change your code but it is open to add new functionality.
Check out below SomeEnum
and SomeClass
:
public enum SomeEnum
{
Type1,
Type2
}
public class SomeClass
{
public void SomeFunction(SomeEnum someEnum)
{
if(someEnum == SomeEnum.Type1)
{
// do something
}
else
{
// do another thing.
}
}
}
Even use else statements for the rest of thing, in this case else statement in SomeFunction
represents SomeEnum.Type2
. If you write your code like that, it is not close because adding Type3
to SomeEnum
will effect this function. To avoid this problem, we can change if-else statement or use switch-case statements. It is also open to add new things.
public class SomeClass
{
public void SomeFunction(SomeEnum someEnum)
{
switch(someEnum)
{
case SomeEnum.Type1:
// do something for Type1
break;
case SomeEnum.Type2:
// do something for Type2
break;
// case SomeEnum.Type3:
// open to adding type 3. Even don't add, there is no error or
// thing violates business rule.
// do something for Type3
// break;
}
}
}
Conclusion, you don't violate OCP, it is actually ISP and if your all classes which implement IRepository<T>
should have Delete
function, then implement it to IRepository<T>
, otherwise create new interface that has Delete
function and implement IRepository<T>
and use it.