In most of my code nowadays, I adapted to an approach which I think I read in the context of “Clean Code”. It was some years ago and I cannot find the source again, so I would like to know what the name of this pattern really is (and if it’s even a pattern).
The approach is so simple, yet powerful that I am baffled as to how hard it is to find sources on this, but that might just be lack of proper search words.
The approach is, in order to write unit-testable code, to decouple the function and presentation of an application (duh) in such a way, that the two parts actually communicate via an interface which I always describe as “HTTP-Like”.
That is, the functions your code can do are one project, and the display etc. are another project. The only communication between the two is done by using Context
classes, which accept a Request
and return a Response
for anything your code can do.
So, e.g. if your code translates a sentence, you’d have a TranslationContext
, along with the TranslationRequest
(which has a property text
) and the TranslationResponse
(with a property text
that includes the translated text).
The Context
class is the only interface from your actual application code to the “outside”, whereas the “view” is also seen as the outside.
From the presentation side, you’ call
TranslationContext ctx = new TranslationContext(interfacedDbOrTextfile);
TranslationRequest req = new TranslationRequest("hallo welt");
TranslationResponse resp = ctx.Process(req);
Console.Write(resp.Text); // "hello world"
Additionally, any data sources (DB, Text files, etc) must be interfaced and decoupled when passed to the core, so you can always replace them with UnitTestable things like in-memory strings instead of textfiles or arraylists instead of database rows.
Is what I am describing just the application of known patterns in a way that I cannot see? Or is it a pattern which was not described yet? Or am I just using different words for things that already exist?
6
The Context Object is a pattern used in a number of places, including J2EE, ASP.NET MVC and Entity Framework. It is used “to encapsulate state in a protocol-independent way to be shared throughout your application.”
Context Object is a controversial pattern. Although it can be thought of as a means of Inversion of Control or Dependency Injection, it’s really more like a convenient way of passing the working environment around (akin to a “god object.”) Context objects can be difficult to mock, therefore testability of the code that uses them is negatively impacted.
Further Reading
Context Object
Passing around ginormous context objects
Mocking HttpContext
Requests and responses are just message passing.
1