Encapsulation Failures

Gareth Rees posted an amusing and detailed review of encapsulation failures, in the context of mobile game apps.

When objects interact with each other, the outcome of events can depend on the properties of several objects. For example, when two objects collide the result depends on the properties of both objects. Consider collisions in a game with bullets, people, and tanks:

  • Bullet/bullet: both unaffected (treat as if they didn’t collide).
  • Bullet/tank: bullet ricochets, tank unaffected.
  • Bullet/person: bullet vanishes, person damaged.
  • Tank/tank: both tanks stop.
  • Tank/person: person stops, tank unaffected.
  • Person/person: both people stop.

You can coerce this kind of table of interactions into the straightjacket of single-dispatch method calls, but the results are pretty ugly however you do it. (It’s no coincidence that the main motivating example in Wikipedia’s multiple dispatch article is collision resolution.)

But there are more subtle examples where the naïve approach goes wrong.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.