Adding Anti-Corruption-Layers to Your Web Application
I've been using anti-corruption layers in my React + Redux apps for a while now. It's a helpful design pattern when asynchronous data your receiving is difficult to work with or needs some sanitation before you let it into your application state.
What is an Anti-Corruption-Layer?
An Anti-Corruption-Layer is a layer between different subsystems that don't share the same semantics.
For me, these layers are functions that enhance or transform data just before it enters my global state, or just after it leaves.
I'll be demonstrating some simple examples of how I have used anti-corruption-layers to make global state management a bit easier on myself.
Enhancing Data
Let's say you expect to receive a user record structured like this
And you need to build a page that looks like this
I like my components to do as little work as possible, so I'll create a new interface with some helper variables that extend my original User. I'll save the extended version to my application state.
I'll add three new values to make rendering the UI easier.
Now I need to add two functions, one that takes an IUser and returns my IUserState.
Another takes an IUserState and returns an IUser.
I'll use these two functions just before the user enters my application, and just before it gets sent to my backend.
Now I have an anti-corruption layer to elp make building my interface easier.
Transforming Data
It's common for a single object to be split into numerous components.
In the user object defined earlier, there's an optional field called billingInfo. In most cases, I would separate the user's billing information into a different component. In that case, I'll assign billing its own slice in my state.
This time I'll make two functions, one that separates the billingInfo from the user, and another that adds it back.
These are the models I'll be working with:
I need two functions for transformation
And finally, we add the functions in the same place as before
With this in place, my state more closely resembles the UI views I am building.
Great article!
Just a question: is there a reason your IUserState interface has “daysRemainingInTrial” but your buildStateUser and buildBackendUser functions have “daysUntilExpiration”? Shouldn’t they be the same?
nope, that’s a typo, I’ll fix it.
Glad you enjoyed the article.