Iterative Coding

Russ Penska15/06/2020

Using The Adaptor Pattern To Hide Bad APIs

The Adaptor Pattern is excellent for keeping your code clean even when using messy third-party APIs.

Let's say you're using a third party library (maybe a nuget package) with the interface below:

public IHorriblePrinter
{
  // method you want to use
  int Print(string text);
  
  // methods you don't care about
  int Print(string text, bool reversed);
  int Print(string text, bool reversed, string extraText);
  
  // lots of extra methods you don't need... 
  ...
}

And you have some code using this interface:

IHorriblePrinter printer = ...
printer.Print("Some words I want to print!");

The problem here is that your code now depends on the IHorriblePrinter interface. This is annoying for a few reasons:


The first step to solving this is to write the interface we wish we were working with. In this case that's quite simple:

public interface INicePrinter
{
  void Print(string text);
}

Now we have a nice interface we can change our code to use this interface we need a way of using it. That's where the adaptor comes in:

public class HorriblePrinterAdaptor : INicePrinter
{
  public HorriblePrinterAdaptor(IHorriblePrinter horrible)
  {
    _horrible = horrible
      ?? throw new ArgumentNullException(nameof(horrible));
  }

  public void Print(string text)
  {
    _horrible.Print(text);
  }
}

This class is the adaptor. It:


The final step is to change our code to use the new class:

IHorriblePrinter printer = ...
IHorriblePrinter horriblePrinter = ...
INicePrinter printer = new HorriblePrinterAdaptor(horriblePrinter);
printer.Print("Some words I want to print!");

Let's revisit our checklist of terrible things:

Back home

Copyright © 2020 Russ Penska