Codementor Events

Adding Anti-Corruption-Layers to Your Web Application

Published Apr 13, 2021Last updated Oct 09, 2021
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

example

And you need to build a page that looks like this

Screen Shot 2021-04-10 at 5.55.02 PM.png

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.

example

Now I need to add two functions, one that takes an IUser and returns my IUserState.

example

Another takes an IUserState and returns an IUser.

example

I'll use these two functions just before the user enters my application, and just before it gets sent to my backend.

example

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:

example

I need two functions for transformation

example

And finally, we add the functions in the same place as before

example

With this in place, my state more closely resembles the UI views I am building.

Discover and read more posts from Jesse Langford
get started
post commentsBe the first to share your opinion
Mike Figueroa
3 years ago

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?

Jesse Langford
3 years ago

nope, that’s a typo, I’ll fix it.

Glad you enjoyed the article.

Show more replies