|category:||War Stories and Advice|
There is a Design Pattern, somtimes called “Don’t Talk to Strangers” that embodies the OO design principle of “Responsibility Assignment”. This pattern can also be called “The Opacity Principle.”
Sometimes I like to describe it as “If you don’t control it, it’s none of your business what’s under the hood.” It isn’t really a design pattern, because it isn’t constuctive; it’s more of a principle, because it informs the selection of patterns.
It is a subtle principle, and violations are sometimes hard to detect. I like to use the “Mutability Test” to discover improper allocation of reponsibility, and violations of the “Don’t Talk to Strangers” principle.
A notable recent example is a designer who was managing the surrogate keys generated by a database, and wanted a class that embodied everything he know about those surrogate keys. They were, essentially, longs, but with some constraints that had been imposed by the DBA.
Developing a class to embody knowledge that is properly the responsibility of the RDBMS violates the “Don’t Talk to Strangers” principle. In this case, the violation is subtle, but made apparent when considering the impact of a change.
This is too much interdependency between database constraints and application program constraints.
It is better to simply treat the database key as a piece of opaque data. The current implementation uses long, a future implementation may change to String or BigDecimal. No further assumptions are made about the surrogate key.
Another test of opacity is to note that the class would have no methods. An object would be created by an Insert, and must be used for Queries, Updates and Deletes.