Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 60 down vote accepted

Imagine you have to use someone else's code designed as about 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 depending on it looks quite often like as follows...

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'd want to make it easier to use, in particular to get rid of repetitive usage of parameters that isn't just needed for your application.

Okay, so you start building 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 exposing it to your "main code" in a way that makes better sense to you.

Layer code would look like below:

    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.

share|improve this answer
1  
How does this scale if there is a whole structure of dependant API classes? Is it still more manageable then the layer it's protecting the rest of the application from? –  Knownasilya Jan 22 '13 at 18:12
    
@Knownasilya that's a very good question, answer expanded to address that –  gnat Jan 22 '13 at 18:36
1  
You read my mind about the whole API/Adapter and Facade vs Anti-Corruption. –  Knownasilya Jan 23 '13 at 1:38
1  
@Neil I think that would be the Facade and Adapter patterns, since JPA is a good ORM specification, in my opinion. –  Knownasilya Jan 23 '13 at 14:58
1  
@Knownasilya, that's an excellent observation, you're probably right. –  Neil Jan 23 '13 at 15: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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.