What is an Anti-Corruption layer, and how is it used?

I’m trying to figure out what the Anti-Corruption layer really means. I know that it’s a way to transition/work around legacy code or bad APIs. What I don’t understand is how it works and what makes it a clean separation from the undesirable layer.

I’ve done some searching, but I can’t find any simple examples or explanations, so I’m looking for someone who understands it and can explain it with simple examples. An answer that would satisfy my question should be simple (not necessarily short), and provide understandable examples of implementation and use.

See this question, for my use case.

Imagine you have to use someone else’s code that is designed as shown below:

    class Messy {
        String concat(String param, String str) { /* ... */ }
        boolean contains(String param, String s) { /* ... */ }
        boolean isEmpty(String param) { /* ... */ }
        boolean matches(String param, String regex) { /* ... */ }
        boolean startsWith(String param, String prefix) { /* ... */ }
    }

Now imagine you find out that your code that depends on it looks like the following:

String process(String param) {
    Messy messy = new Messy();
    if (messy.contains(param, "whatever")) {
        return messy.concat(param, "-contains");
    }
    if (messy.isEmpty(param)) {
        return messy.concat(param, "-empty");
    }
    if (messy.matches(param, "[whatever]")) {
        return messy.concat(param, "-matches");
    }
    if (messy.startsWith(param, "whatever")) {
        return messy.concat(param, "-startsWith");
    }
    return messy.concat(param, "-whatever");
    // WTF do I really need to repeat bloody "param" 9 times above?
}

…and that you want to make it easier to use, in particular, to get rid of repetitive usage of parameters that just aren’t needed for your application.

Okay, so you start building an anti-corruption layer.

  1. First thing is to make sure that your “main code” doesn’t refer to Messy directly. For example, you arrange dependency management in such a way that trying to access Messy fails to compile.

  2. Second, you create a dedicated “layer” module that is the only one accessing Messy and expose it to your “main code” in a way that makes better sense to you.

Layer code would look like the following:

    class Reasonable { // anti-corruption layer
        String param;
        Messy messy = new Messy();
        Reasonable(String param) {
            this.param = param;
        }
        String concat(String str) { return messy.concat(param, str); }
        boolean contains(String s) { return messy.contains(param, s); }
        boolean isEmpty() { return messy.isEmpty(param); }
        boolean matches(String regex) { return messy.matches(param, regex); }
        boolean startsWith(String prefix) { return messy.startsWith(param, prefix); }
    }

As a result, your “main code” does not mess with Messy, using Reasonable instead, about as follows:

String process(String param) {
    Reasonable reasonable = new Reasonable(param);
    // single use of "param" above and voila, you're free
    if (reasonable.contains("whatever")) {
        return reasonable.concat("-contains");
    }
    if (reasonable.isEmpty()) {
        return reasonable.concat("-empty");
    }
    if (reasonable.matches("[whatever]")) {
        return reasonable.concat("-matches");
    }
    if (reasonable.startsWith("whatever")) {
        return reasonable.concat("-startsWith");
    }
    return reasonable.concat("-whatever");
}

Note there is still a bit of a mess messing with Messy but this is now hidden reasonably deep inside Reasonable, making your “main code” reasonably clean and free of corruption that would be brought there by direct usage of Messy stuff.


Above example is based on how Anticorruption Layer is explained at c2 wiki:

If your application needs to deal with a database or another application whose model is undesirable or inapplicable to the model you want within your own application, use an AnticorruptionLayer to translate to/from that model and yours.

Note example is intentionally made simple and condensed to keep explanation brief.

If you have a larger mess-of-API to cover behind the anti-corruption layer, same approach applies: first, make sure your “main code” doesn’t access corrupted stuff directly and second, expose it in a way that is more convenient in your usage context.

When “scaling” your layer beyond a simplified example above, take into account that making your API convenient is not necessarily a trivial task. Invest an effort to design your layer the right way, verify its intended use with unit tests etc.

In other words, make sure that your API is indeed an improvement over one it hides, make sure that you don’t just introduce another layer of corruption.


For the sake of completeness, notice subtle but important difference between this and related patterns Adapter and Facade. As indicated by its name, anticorruption layer assumes that underlying API has quality issues (is “corrupted”) and intends to offer a protection of mentioned issues.

You can think of it this way: if you can justify that library designer would be better off exposing its functionality with Reasonable instead of Messy, this would mean you’re working on anticorruption layer, doing their job, fixing their design mistakes.

As opposed to that, Adapter and Facade do not make assumptions on the quality of underlying design. These could be applied to API that is well designed to start with, just adapting it for your specific needs.

Actually, it could even be more productive to assume that patterns like Adapter and Facade expect underlying code to be well designed. You can think of it this way: well designed code shouldn’t be too difficult to tweak for particular use case. If it turns out that design of your adapter takes more effort than expected, this could indicate that underlying code is, well, somehow “corrupted”. In that case, you can consider splitting the job to separate phases: first, establish an anticorruption layer to present underlying API in a properly structured way and next, design your adapter / facade over that protection layer.

13

To quote another source:

Create an isolating layer to provide clients with functionality in
terms of their own domain model. The layer talks to the other system
through its existing interface, requiring little or no modification to
the other system. Internally, the layer translates in both directions
as necessary between the two models.

Eric Evans, Domain Driven Design, 16th printing, page 365

The most important thing is that different terms are used at each side of the anti corruption layer. I was once working on a system for transportation logistic. Rounds had to be planned. You had to equip the vehicle at a depot, drive to different customer sites and service them and visit other places, like a tank stop. But from the higher level this was all about task planning. So it made sense to separate the more general task planning terms from the very specific transportation logistic terms.

So an anti corruption layers isolation is not just about protecting you from messy code, it is to separate different domains and make sure that they stay separated in the future.

1

Adapter

When you have incompatible interfaces, that perform similar logic, to adapt one into the other, so that you can use implementations of one with things that expect the other.

Example:

You have an object that wants a Car, but you only have a 4WheelVehicle class, so you create a CarBuiltUsing4WheelVehicle and use that as your Car.

Facade

When you have a complex/confusing/gigantic API and you want to make it simpler/clearer/smaller. You will create a Facade to hide away the complexity/confusion/extras and only expose a new simple/clear/small API.

Example:

You are using a library that has 100 methods, and to perform certain task you need to do a bunch of initialization, connecting, opening/closing things, just to finally be able to do what you wanted, and all you wanted is 1 feature of all 50 the library can do, so you create a Facade that has only a method for that 1 feature you need and which does all the initializing, cleaning, etc. for you.

Anti-corruption Layer

When you have a system that’s out of your domain, yet your business needs requires you to work with that other domain. You do not want to introduce this other domain into your own, therefore corrupting it, so you will translate concept of your domain, into this other domain, and vice-versa.

Example:

One system views the custumer having a name and a list of strings, one for each transactions. You view Profiles as stand alone classes having a name, and Transactions as stand alone classes having a string, and Customer as having a Profile and a collection of Transactions.

So you create an ACL layer that will let translate between your Customer and the other system’s Customer. This way, you never have to use the other system’s Customer, you simply need to tell the ACL: “give me the Customer with Profile X, and the ACL tells the other system to give it a Customer of name X.name, and returns you a Customer with Profile X.

====================

All three are relatively similar, because they are all indirection patterns. But they address different structures, classes/objects versus APIs versus modules/sub-systems. You could have them all combined if you needed to. The sub-system has a complex API, so you build a FACADE for it, it uses a different model, so for each data representation that don’t fit your model, you would TRANSLATE that data back into how you model it. Finally, maybe the interfaces are also incompatible, so you would use ADAPTERS to adapt from one to the other.

1

A lot of answers here say that ACLs are “not just” about wrapping messy code. I’d go further and say they are not about that at all, and if they do then that is a side benefit.

An anti-corruption layer is about mapping one domain onto another so that services that use second domain do not have to be “corrupted” by concepts from the first. ACLs are to domain models what adapters are to classes, it’s just happening at a different level. The adapter is arguably the most important design pattern – I use it all the time – but judging the wrapped class as being messy or not is irrelevant. It is what it is, I just need it have a different interface.

Focussing on messiness is misleading and misses the point of what DDD is about. ACLs are about dealing with conceptual mismatches, not poor quality.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật