segunda-feira, 14 de setembro de 2015

Anti Corruption Layer Pattern

Today I'll talk about the Anti Corruption Layer Pattern mentioned on Eric Evans's book Domain Driven Design.

New systems usually have the need to communicate with legacy to dispose of some feature. The new system's model probably is different from the legacy model, considering that legacy model is usually weak. This discrepancy results in compatibility problems when integrating these two systems. Two systems with a well designed model wouldn't have this problem.

When this communication is required, the new model can be badly affected/influenced, because probably there will be a difficulty communicating both systems due to incompatibilities, for example, different data structures, protocols, and even pieces of the model. This can result in the distortion of the new model because of the need of the link between the new generation and the legacy.

One solution for this problem is a layer between both systems doing this adaptation, exposing the feature required through interfaces abstracting details of the implementation. This is the Anti Corruption Layer, a layer that makes this adaptation and the "dirty work", building a layer responsible for doing this translation. It's usually done through services exposing interfaces well defined with the required features.

One way for building the Anti Corruption Layer is by mixing the patterns Facade and Adapter, that are also mentioned on the book Domain Driven Design.

The facade is an alternative that simplify the access to a sub system. It exposes the features hiding implementation details, leaving for the consumer just the work of referencing the interface representing the feature. The adapter is like a wrapper that allows two incompatible functionalities to work together. It does the job of adapting the feature, creating a compatible interface between both implementations. These patterns will can be better explained with examples in a future post.

The image below shows two systems and the Anti Corruption Layer between them using these two patterns to hide the implementation details and to do the adaptability between them.

The Anti Corruption Layer's main goal is to link two bounded contexts/sub systems, and preserve the new model by not polluting it with possible problems when integrating with other sub systems.

It's always good to emphasize the importance of creating tests when doing this kind of integration, the tests will assert that the implementation is doing what is expected, avoiding surprises ahead.