I have spent most of my afternoon reading on the Open/Closed Principle, and I can't seem to understand it fully. Here are some referred articles I have read already and it seems as I missed something.
- Understanding the Open Closed Principle
- The end of dependency injection - who creates the dependencies?
Let's say I have a base generic repository which exposes some of the most generic methods expected to fit any needs from a repository.
Repository
public abstract class Repository<TModel> where TModel : class {
protected Repository() { }
public abstract IList<TModel> FilterBy(
Expression<Func<TModel, bool>> filterExpression);
public abstract IList<TModel> GetAll();
public abstract TModel GetById(int id);
public abstract Save(TModel instance);
}
Then, I wish to specialize into a ProductRepository.
ProductRepository
public abstract class ProductRepository : Repository<Product> {
protected ProductRepository() : base() { }
}
Let's assume that I have all I need from the base repository here. If so, then I feel like I'm not breaking the Open/Closed Principle, because I'm not defining any new members or the like.
However, should I need a special kind of repository, let's say an AlertLevelConfigurationRepository, and the business requirement states that I can have only one AlertLevelConfiguration at a time. So, the repository needs to always get the current configuration.
AlertLevelConfigurationRepository
public abstract class AlertLevelConfigurationRepository
: Repository<AlertLevelConfiguration> {
protected AlertLevelConfigurationRepository() : base() { }
public abstract AlertLevelConfiguration GetCurrent();
}
Now, I feel like I break the Open/Closed Principle because of this new method because this class is a modified derived type from its ancestor. It is modified as the base definition of a repository doesn't offer this GetCurrent
method. Besides, I'm quite sure I will never use the any of the base method, given the exception of the Save
method, since the alter level configuration can be, well, configurable!
In the end, I wonder whether I understand the Open/Closed Principle, and somehow I doubt I do.
I'd like to know if this is an example where the principle is broken, and if not, then I'd like to get the some explanations over the principle itself.