Dave Archer
Dave Archer

Reputation: 3060

Is this the Open/Closed principle? And if not

Considering the following code

public interface IEntity {
int Id { get; set; }
}

public class User : IEntity {
    public int Id { get; set; }
}

public abstract class RepositoryBase<TEntity> where TEntity : IEntity {

    public bool Save(TEntity entity) {
        if (!IsValid(entity)) return false;

        // Write to data store

        return true;
    }

    public abstract TEntity CreateNew();

    protected abstract bool IsValid(TEntity entity);
}


public class UserRepository : RepositoryBase<User> {

    public override User CreateNew() {
        return new User {
            Id = 3
        };
    }

    protected override IsValid(User entity) {
        return entity.Id > 0;
    }
}

Is this the open/closed principle? i.e deferring most of the responsibility to the base class and allowing certain functional responsibilities to inheriting classes.

It doesn't feel like it is, so if it not the open/closed principle then what kind of design pattern is this?

Cheers

Upvotes: 0

Views: 282

Answers (2)

Fuhrmanator
Fuhrmanator

Reputation: 12882

As you can read on wikipedia, the OCP has a couple of definitions. The one that's probably mostly used on stackoverflow is the polymorphic one. I prefer the protected variations spin, since ideally we want to have a design that allows for variations in one place, which don't affect certain (protected) classes that depend on those variations.

In your example, the variations in the implementations of IEntity would not affect the client classes that use IEntities, provided you don't have direct coupling between the clients and the implementations. That is, clients should only know about IEntities and not about specific implementations. This often requires implementing a factory so that clients can access implementations without knowing them concretely.

Upvotes: 1

Don Roby
Don Roby

Reputation: 41137

You can create new repositories for different data structures by extending RepositoryBase<TEntity> in different ways, without having to modify the code in RepositoryBase<TEntity>. That is the core meaning of the open/closed principle.

That said, the open/closed principle is a general design principle and not a design pattern. The main design pattern visible in the relation of the Save and IsValid methods is Template Method.

Upvotes: 2

Related Questions