Role Hints by Mark Seemann
This article provides an overview of different ways to hint at the role an object is playing.
One of the interesting points in Lean Architecture is that many so-called object-oriented languages aren't really object-oriented, but rather class-oriented. This is as true for C# as for Java. The code artifacts are classes (or interfaces, etc.); not objects.
When asked to distinguish, most of us understand that objects are instances of classes, but since the languages are centered around classes, we sometimes forget this distinction and treat objects and classes as one and the same. When this happens, we run into some of the problems that Udi Dahan describes in his excellent talk Making Roles Explicit. The solution is proposed in the same talk: make roles explicit.
So, what's a role? you might ask. A role is the purpose of an object instance in a given context. (That sounds a bit like the (otherwise rather confusingly described) concept of DCI.) An object can play more than one role during its lifetime, or a class can be instantiated in one of the roles it can play. Some objects can play only a single role.
There are several ways to hint at the role played by an object:
- Type Name. Use the name of the type (such as the class name) to hint at the role played by instances of the class. This seems to be mostly relevant for objects that can play only a single role.
- Argument Name. Use the name of an argument (or variable) to hint at the role played by an instance.
- Metadata. Use data about code (such as attributes or marker interfaces) to hint at the role played by instances of the class.
- Role Interfaces. A class can implement several Role Interfaces; clients can treat instances as the roles they require.
- Partial Type Name. Use part of the type name to hint at a role played by objects. This can be used to enable Convention over Configuration.
Making the role of an object explict can tip the balance in favor of true object-orientation instead of class-orientation. It will likely make your code easier to read, understand and maintain.