Entity interface anti-pattern

This has been discussed many times before on various mailing lists, and I’m sure there are blog posts about it that are eluding me currently, but I’ll put it out there anyway.

 

Interfaces on entities are an anti-pattern

(when they’re in the vein of ICustomer and Customer)

 

This smells of applying a rule a little too broadly. People are (rightly) being urged to program to abstractions, to decouple and explicitly reveal their dependencies. Programming to abstractions is nearly always a good thing, but rules are often accompanied by exceptions, and in this case it’s entities that are the exception.

Lets take a step back and remind ourselves why abstractions are useful, specifically programming to interfaces.

  1. It lets us program against a contract, rather than a concrete implementation
  2. We can design multiple implementations of an interface, without altering dependencies
  3. We can substitute implementations at will

Taking a typical service example, it’s much better for a TextWriter to depend on a IStream than it is to depend on a FileStream, because we could substitute the stream for a MemoryStream or a more high-level XmlStream without changing the design; if we didn’t have this abstraction we wouldn’t have the flexibility. A side-effect of this ability is greatly improved testability.

Back to entities. Here are some tell-tale signs that you’re might be implementing an anti-pattern:

  1. Your interface signature identical to your class
  2. There’s only one implementation of your interface
  3. Your entity has no behavior to abstract, yet you’ve created an abstraction anyway

Signatures

A contract specifies what functionality an instance should provide. An implementation will rarely be of the same size (method count wise) as the contract because it will have additional code dedicated to how it provides the expected behavior. If the only thing your class does is exist purely to provide backing fields for your interface’s properties and methods, then it’s fairly redundant to have both the class and interface. It’s duplication for the sake of an abstraction that provides no benefits.

Implementations

Excluding cases when you have an inheritance hierarchy mapped, you won’t have more than one implementor of an entity interface; you’ll simply have ICustomer and Customer, IProduct and Product. What’s the point in being able to substitute implementations when there’s guaranteed to only ever be one? Again, a redundant design when used with entities.

Behavior

Abstraction is about allowing consumers of your object to use it without knowledge of the actual implementation. The behavior that an entity contains should mostly concern only itself (such as state changes, adding and removing children, etc…); this kind of behavior has no side-effects and can rarely vary in implementation, therefore entities don’t need abstractions.

What about testability? With changes only affecting itself, the entities themselves can be used in tests, so there’s no need to mock them.

What’s a good example of interfaces on an entity?

Like any rule, there are exceptions; in this case it’s when your interface doesn’t fit the 3 rules mentioned above. Interfaces should be logical components that are combined to make a single unit; they can be used to contain sub-sections of behavior that are implemented by multiple entities. This design allows you to create services that depend on the specific piece of behavior, rather than an a whole entity, thus giving you a service that can be used with many entities (and ones that don’t exist yet) without changing the design. For example, given House, Car, and Wall classes, if each of these implemented an IPaintable interface, a service could instruct these entities to be painted without knowing (or caring) what kind of entity it was dealing with (specifically, without creating an overload for each entity type).

 

Don’t apply rules blindly, understand what you’re doing and why you’re doing it.

File this one under things we all already knew.

 

Edit: Updated the behavior section to be less controversial (and more correct!) and added the good example

Related Articles:

    Post Footer automatically generated by Add Post Footer Plugin for wordpress.

    This entry was posted in design, orm, things we all already knew. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
    • http://fabiomaulo.blogspot.com/ Fabio Maulo

      class Vehicle: IVehicle, IVehicleInfo
      class Car: Veicle, ICar, ICarInfo
      class CarDTO : ICarInfo
      ….
      ShowCars(IEnumerable cars)

      Which will be the implementation passed to ShowCars method ?

    • Anonymous

      “Entities are purely data structures, and as there’s no variance in how you can implement a structure, there’s nothing that can be gained from abstracting it.” Speaking of anti-patterns: http://martinfowler.com/bliki/AnemicDomainModel.html

    • http://blog.schuager.com Germán Schuager

      Fabio, I can see some uses for something like ICarInfo, but what do you gain with IVehicle or ICar?

    • Justice

      Anonymous is right, in the sense that you assume that your domain model entities should have no behavior. But the opposite is true. Your domain model entities should be rich with behavior, and should certainly be tested. However, all non-pure concerns (persistence, logging, etc) should be done outside of the domain model: persistence with an ORM like NHibernate and logging with interceptors. Therefore, there is no need to have your domain model entities be interfaces: your domain model is perfectly testable on its own, as fully concrete and fully implemented behavior-rich classes.

    • http://devlicio.us/blogs/casey Jak Charlton

      An anemic domain is an anti-pattern ….

      1-1 interfaces to classes is also an anti pattern …

      The first is the worst of the two

      Entities should and must include behaviour – otherwise they are DTOs not entities (in any real usage of the word)

      To solve the second anti pattern – interfaces should be use case based around entities, or preferably around aggregate roots (to use the DDD term).

      SO instead of
      Customer : ICustomer

      you have
      Customer: IUpgradeableToPreferred, ICanPlaceAnOrder

      etc etc …. which combines ISP, with avoiding the interface anti-pattern, and putting your domain logic on your entities to avoid an anemic model

    • http://www.lostechies.com/members/jagregory/default.aspx James Gregory

      To those who mentioned the anemic domain, you are of course right; I should have been a little clearer on what I meant by having no behavior.

      Entities should have behavior that concerns their own state, and anything directly related to them. Jak’s examples fall into that category. They should not know how to save themselves (unless you’re doing AR), log themselves, query themselves, etc… That’s the kind of behavior I was referring to (albeit not very clearly).

      Again, Jak’s examples are exactly what I’m not talking about in this post. Those are a good example of interfaces on entities. They are a subset of behavior, which can be applied to multiple entities; not a single interface per entity.

    • http://blogs.lessthandot.com chrissie1

      There is a use for interfaces on domain entities, and I think I heard this of Udi Dahan. When you use the tell don’t ask principle on your entites you won’t have a need for properites but that makes for difficult unittesting. So you can have an interface that only has methods and an implementation that also has properties for unittesting or peristence. Then you just pass the interface around and don’t need to worry about people using the properties.

      So there can be a reason for interfaces on entites, ok they are not bu still 1:1.

    • http://theusualsuspect.com John Polling

      Having read your article has made me realise I need to be more careful about the behaviours I’m putting into my service layers that should probably be going into my entities.

    • http://home.infusionblogs.com/kszklenski/default.aspx Kyle Szklenski

      I’ve seen numerous places where an interface was used to provide only properties. It made me sick. I think doing that basically has the interface implying implementation, or what data is allowed to be stored in the implementing classes. What would the difference be if those weren’t properties at all, but were allowed to be data members directly? Sometimes those properties return abstract types, which is better, but it still seems largely pointless to me to have an interface with just properties. Good post.