The Single Responsibility Principle states that:
A class should have one, and only one, reason to change.
The Open/Closed Principle states that:
You should be able to extend a classes behavior, without modifying it.
How can a developer respect both principles if a class should have only one reason to change, but should not be modified?
Example
The factory pattern is a good example here of something that has a single responsibility, but could violate the open/closed principle:
public abstract class Product
{
}
public class FooProduct : Product
{
}
public class BarProduct : Product
{
}
public class ProductFactory
{
public Product GetProduct(string type)
{
switch(type)
{
case "foo":
return new FooProduct();
case "bar":
return new BarProduct();
default:
throw new ArgumentException(...);
}
}
}
What happens when I need to add ZenProduct
to the factory at a later stage?
- Surely this violates the open/closed principle?
- How can we prevent this violation?
ZenProduct
violates the principle. I agree that extending the factory would prevent this violation, however it's a lot of overhead, plus you'd also have to violate the OCP elsewhere, because you'd have to modify a class to use the new factory. – Missis