Adapter
Definition
Adapter
- In plain English
- An adapter wraps a type with the wrong interface so it can be used where a different interface is expected.
- Think of it like
- It is like a travel plug adapter that lets a UK plug fit a European socket.
Why it exists
Your refill service expects Check to return approval and an error. The insurer client accepts XML and returns numeric codes.
Repeating conversions across callers spreads the insurer’s quirks. Put the translation in one wrapper.
How it works
Third-party SDK
- In plain English
- A third-party SDK is code from another company that you use but can't change.
- Think of it like
- Like a rented appliance you can plug in but not rewire.
XML
- In plain English
- XML is a text format that uses named tags to describe data.
- Think of it like
- It is like labelled envelopes showing what each piece of information contains.
package adapters
import (
"encoding/xml"
"errors"
"fmt"
)
type Insurer interface{ Check(string) (bool, error) }
type LegacyClient struct{}
func (LegacyClient) VerifyClaim(payload string) int { return 200 }
type LegacyInsurerAdapter struct{ client LegacyClient }
func (a LegacyInsurerAdapter) Check(rx string) (bool, error) {
payload, err := xml.Marshal(struct{ Code string }{Code: rx})
if err != nil {
return false, err
}
switch a.client.VerifyClaim(string(payload)) {
case 200:
return true, nil
case 403:
return false, nil
default:
return false, errors.New("insurer unavailable")
}
}
func Demo() {
var insurer Insurer = LegacyInsurerAdapter{LegacyClient{}}
fmt.Println(insurer.Check("RX&42"))
}
LegacyInsurerAdapter satisfies Insurer and delegates translated calls to LegacyClient.
- State your need
Define the interface your application wants.
- Wrap the outside type
Store the vendor client in a small adapter.
- Translate both ways
Convert inputs, outputs, units and errors.
- Keep callers focused
Callers use your interface; creation code wires up the vendor client.
Examples
Translate insurer responses
The old insurer returns numeric status codes. Your refill code needs approval or an error.
package adapters
import (
"encoding/xml"
"errors"
"fmt"
)
type Insurer interface{ Check(string) (bool, error) }
type LegacyClient struct{}
func (LegacyClient) VerifyClaim(payload string) int { return 200 }
type LegacyInsurerAdapter struct{ client LegacyClient }
func (a LegacyInsurerAdapter) Check(rx string) (bool, error) {
payload, err := xml.Marshal(struct{ Code string }{Code: rx})
if err != nil {
return false, err
}
switch a.client.VerifyClaim(string(payload)) {
case 200:
return true, nil
case 403:
return false, nil
default:
return false, errors.New("insurer unavailable")
}
}
func Demo() {
var insurer Insurer = LegacyInsurerAdapter{LegacyClient{}}
fmt.Println(insurer.Check("RX&42"))
}
Here, 200 means approved and 403 means declined. Other codes become errors; these meanings are assumptions of this demonstration.
The insight
An adapter contains a foreign API’s quirks in one place.
Unify three wearable brands
Three brands expose heart-rate readings differently. You want one HeartRateSource interface.
package adapters
import "fmt"
type HeartRateSource interface{ BPM() int }
type BrandA struct{}
func (BrandA) Pulse() int { return 72 }
type BrandB struct{}
func (BrandB) Rate() int { return 74 }
type BrandC struct{}
func (BrandC) Reading() int { return 73 }
type AdapterA struct{ client BrandA }
func (a AdapterA) BPM() int { return a.client.Pulse() }
type AdapterB struct{ client BrandB }
func (a AdapterB) BPM() int { return a.client.Rate() }
type AdapterC struct{ client BrandC }
func (a AdapterC) BPM() int { return a.client.Reading() }
func Demo() {
sources := []HeartRateSource{AdapterA{BrandA{}}, AdapterB{BrandB{}}, AdapterC{BrandC{}}}
for _, s := range sources {
fmt.Println(s.BPM())
}
}
BPM means beats per minute. These stand-in clients always return valid readings; real adapters must also translate each provider’s errors.
The insight
Adapters let many outside APIs look like one.
Translate temperature units
An old inverter returns Fahrenheit as text. Your monitoring code needs Celsius as a number.
package main
import (
"errors"
"fmt"
"math"
"strconv"
)
type TemperatureSource interface{ Celsius() (float64, error) }
type LegacyInverter struct{}
func (LegacyInverter) Temperature() string { return "77" }
type Adapter struct{ client LegacyInverter }
func (a Adapter) Celsius() (float64, error) {
f, err := strconv.ParseFloat(a.client.Temperature(), 64)
if err != nil {
return 0, err
}
if math.IsNaN(f) || math.IsInf(f, 0) {
return 0, errors.New("invalid temperature")
}
return (f - 32) * 5 / 9, nil
}
func main() { var s TemperatureSource = Adapter{LegacyInverter{}}; fmt.Println(s.Celsius()) }
Parsing can fail, so the adapter returns an error. It also rejects nonfinite readings before converting units.
The insight
Adapters translate units and formats as well as method names.
Trade-offs
Pros
- Callers use a clean interface.
- Provider-specific translations stay together.
Cons
- Adds one type per provider.
- Conversions can lose information.
Use when
- An outside library cannot be changed.
- Units or error formats differ.
Avoid when
- You own both sides and can align them.
- The existing type already satisfies your interface.
Quick check
Takeaways
- An adapter makes a mismatched type fit your interface.
- It keeps foreign quirks in one place.
- Use it for code you can't change.