Patterncore
Separated interface
Also called Separated Interface, interface in the client package, required interface.
A separated interface is an interface defined in one package and implemented in another, so that the client depends only on the interface and a dependency can point against the layers.
- Family
- architectural
- Intent
- Define an interface in a separate package from its implementation.
Intent
A separated interface "Defines an interface in a separate package from its implementation."1 The client depends only on the interface. The implementation can be in a package that the client does not know, and that the client may not even be allowed to depend on.
Problem
A good structure of packages has rules about which package may use which. For example, the domain layer may not call the infrastructure, which sends emails and talks to the database. The catalog says: "However, you might need to invoke methods that contradict the general dependency structure."1
The order code in the domain must send a confirmation, but the code that sends emails is in the infrastructure. If the domain imports the email class, the dependency points the wrong way, the domain can no longer be built or tested without the infrastructure, and the packages can form a cycle.
Solution
The catalog says to "use Separated Interface to define an interface in one package but implement it in another."1 The parts are:
- The interface. It is in the package of the client, or in a small package of its own, and it is written in the terms of the client.
- The client. It uses only the interface. "This way a client that needs the dependency to the interface can be completely unaware of the implementation."1
- The implementation. It is in another package, which depends on the package of the interface. The dependency now points from the implementation to the client.
- The code that connects them. Something must create the implementation and give it to the client, such as the main program, a factory, a Plugin or Dependency injection.2
package domain package infrastructure
OrderService --uses--> Notifier <--implements-- EmailNotifier
(depends on domain)
package main: creates EmailNotifier and gives it to OrderService
In the following program, the domain code defines the interface Clock that it needs. The implementation is a separate class.
from typing import Protocol
class Clock(Protocol): # defined in the package that needs it
def now(self) -> str: ...
def stamp(clock: Clock, text: str) -> str: # domain code: knows only the interface
return f"[{clock.now()}] {text}"
class FixedClock: # implemented in another package
def now(self) -> str:
return "10:00"
print(stamp(FixedClock(), "order 7 is confirmed"))
[10:00] order 7 is confirmed
Example
Each example file has sections that stand for packages. The domain section defines the interface Notifier and the class OrderService, which confirms an order through the interface. The infrastructure section has EmailNotifier, which implements the interface. The tests section has RecordingNotifier, which keeps the messages in a list. Only main knows both: it confirms order 7 with the email notifier and order 8 with the recording notifier, as a unit test does.
from typing import Protocol
# ---- package domain: it defines the interface that it needs, and imports nothing below.
class Notifier(Protocol):
def send(self, customer: str, text: str) -> None: ...
class OrderService:
def __init__(self, notifier: Notifier):
self.notifier = notifier
def confirm(self, number: int, customer: str) -> None:
self.notifier.send(customer, f"order {number} is confirmed")
# ---- package infrastructure: it imports the domain and implements its interface.
class EmailNotifier:
def send(self, customer: str, text: str) -> None:
print(f"email to {customer}: {text}")
# ---- package tests: another implementation of the same interface.
class RecordingNotifier:
def __init__(self):
self.sent = []
def send(self, customer: str, text: str) -> None:
self.sent.append(f"{customer}: {text}")
# ---- main: the only code that knows both the domain and the implementations.
OrderService(EmailNotifier()).confirm(7, "ann")
recorder = RecordingNotifier()
OrderService(recorder).confirm(8, "bob")
print("the test notifier recorded:", "; ".join(recorder.sent))
email to ann: order 7 is confirmed
the test notifier recorded: bob: order 8 is confirmed
- Verdict: stdlib.
typing.Protocoldefines the interface in the domain code. A class satisfies it by its methods, with no import of the domain, and a type checker such as mypy checks it. At run time, Python only calls the method. - In a real program, each
----section is its own package. Onlymainimports both the domain and the implementations.
import java.util.ArrayList;
import java.util.List;
public class Main {
// ---- package domain: it defines the interface that it needs, and imports nothing below.
interface Notifier {
void send(String customer, String text);
}
static class OrderService {
private final Notifier notifier;
OrderService(Notifier notifier) { this.notifier = notifier; }
void confirm(int number, String customer) {
notifier.send(customer, "order " + number + " is confirmed");
}
}
// ---- package infrastructure: it imports the domain and implements its interface.
static class EmailNotifier implements Notifier {
public void send(String customer, String text) {
System.out.println("email to " + customer + ": " + text);
}
}
// ---- package tests: another implementation of the same interface.
static class RecordingNotifier implements Notifier {
final List<String> sent = new ArrayList<>();
public void send(String customer, String text) { sent.add(customer + ": " + text); }
}
// ---- main: the only code that knows both the domain and the implementations.
public static void main(String[] args) {
new OrderService(new EmailNotifier()).confirm(7, "ann");
RecordingNotifier recorder = new RecordingNotifier();
new OrderService(recorder).confirm(8, "bob");
System.out.println("the test notifier recorded: " + String.join("; ", recorder.sent));
}
}
email to ann: order 7 is confirmed
the test notifier recorded: bob: order 8 is confirmed
- Verdict: native.
Notifieris a Java interface. In a real program, it is in the package of the domain, andEmailNotifieris in a package that imports it. With modules, the domain module exports the interface and does not require the infrastructure module.
// ---- module domain: it describes the interface that it needs, and imports nothing below.
// JavaScript has no interface types; the interface is the method send(customer, text).
class OrderService {
constructor(notifier) {
if (typeof notifier.send !== "function") throw new TypeError("notifier needs send()");
this.notifier = notifier;
}
confirm(number, customer) {
this.notifier.send(customer, `order ${number} is confirmed`);
}
}
// ---- module infrastructure: it implements the interface of the domain.
class EmailNotifier {
send(customer, text) {
console.log(`email to ${customer}: ${text}`);
}
}
// ---- module tests: another implementation of the same interface.
class RecordingNotifier {
constructor() {
this.sent = [];
}
send(customer, text) {
this.sent.push(`${customer}: ${text}`);
}
}
// ---- main: the only code that knows both the domain and the implementations.
new OrderService(new EmailNotifier()).confirm(7, "ann");
const recorder = new RecordingNotifier();
new OrderService(recorder).confirm(8, "bob");
console.log("the test notifier recorded:", recorder.sent.join("; "));
email to ann: order 7 is confirmed
the test notifier recorded: bob: order 8 is confirmed
- Verdict: idiom. JavaScript has no interface types, so the interface is a method name and its arguments. The constructor of
OrderServicechecks that the notifier has asendmethod, so that a wrong object fails at once. TypeScript can write the interface as a type.
package main
import (
"fmt"
"strings"
)
// ---- package domain: it defines the interface that it needs, and imports nothing below.
// Notifier is the interface that the domain needs.
type Notifier interface {
Send(customer, text string)
}
type OrderService struct{ notifier Notifier }
func (s OrderService) Confirm(number int, customer string) {
s.notifier.Send(customer, fmt.Sprintf("order %d is confirmed", number))
}
// ---- package infrastructure: it implements the interface. In Go it does not even
// import the domain, because a type satisfies an interface by its methods alone.
type EmailNotifier struct{}
func (EmailNotifier) Send(customer, text string) { fmt.Printf("email to %s: %s\n", customer, text) }
// ---- package tests: another implementation of the same interface.
type RecordingNotifier struct{ sent []string }
func (r *RecordingNotifier) Send(customer, text string) {
r.sent = append(r.sent, customer+": "+text)
}
// ---- main: the only code that knows both the domain and the implementations.
func main() {
OrderService{EmailNotifier{}}.Confirm(7, "ann")
recorder := &RecordingNotifier{}
OrderService{recorder}.Confirm(8, "bob")
fmt.Println("the test notifier recorded:", strings.Join(recorder.sent, "; "))
}
email to ann: order 7 is confirmed
the test notifier recorded: bob: order 8 is confirmed
- Verdict: native. Go interfaces are satisfied by the method set alone, so
EmailNotifierdoes not import the package that definesNotifier. The Go code review guide puts interfaces in the package that uses them, which is this pattern. RecordingNotifierhas a pointer receiver, so the service gets&RecordingNotifier{}and the test can readsentafter the call.
use std::cell::RefCell;
// ---- module domain: it defines the trait that it needs, and uses nothing below.
mod domain {
pub trait Notifier {
fn send(&self, customer: &str, text: &str);
}
pub struct OrderService<'a> {
pub notifier: &'a dyn Notifier,
}
impl OrderService<'_> {
pub fn confirm(&self, number: u32, customer: &str) {
self.notifier.send(customer, &format!("order {} is confirmed", number));
}
}
}
// ---- module infrastructure: it uses the domain and implements its trait.
mod infrastructure {
use crate::domain::Notifier;
pub struct EmailNotifier;
impl Notifier for EmailNotifier {
fn send(&self, customer: &str, text: &str) {
println!("email to {}: {}", customer, text);
}
}
}
// ---- module tests: another implementation of the same trait.
struct RecordingNotifier {
sent: RefCell<Vec<String>>,
}
impl domain::Notifier for RecordingNotifier {
fn send(&self, customer: &str, text: &str) {
self.sent.borrow_mut().push(format!("{}: {}", customer, text));
}
}
// ---- main: the only code that knows both the domain and the implementations.
fn main() {
let email = infrastructure::EmailNotifier;
domain::OrderService { notifier: &email }.confirm(7, "ann");
let recorder = RecordingNotifier { sent: RefCell::new(Vec::new()) };
domain::OrderService { notifier: &recorder }.confirm(8, "bob");
println!("the test notifier recorded: {}", recorder.sent.borrow().join("; "));
}
email to ann: order 7 is confirmed
the test notifier recorded: bob: order 8 is confirmed
- Verdict: native. The trait
Notifieris in the moduledomain, and the moduleinfrastructureuses it withuse crate::domain::Notifier.domaindoes not useinfrastructure. In a larger program, the two modules are two crates. RecordingNotifierkeeps the messages in aRefCell, becausesendtakes&self.
Consequences
Benefits.
- Dependencies follow the rules of the layers. The domain does not depend on the infrastructure, and the cycle is gone.
- Easy tests. A test gives the client a Test double that implements the interface.
- Changeable implementations. A new implementation, such as a text message notifier, needs no change of the client. The catalog says that a separated interface "provides a good plug point for Gateway".1
Liabilities.
Without a separated interface, the client creates the concrete class. In the following program, the domain code makes the email notifier itself, so a unit test of the domain sends a real email.
This code runs but gives a wrong answer on purpose.
class EmailNotifier: # infrastructure
def send(self, customer, text):
print(f"a real email goes to {customer}: {text}")
class OrderService: # domain code that creates the concrete class itself
def confirm(self, number, customer):
EmailNotifier().send(customer, f"order {number} is confirmed")
# A unit test of OrderService cannot replace the notifier.
OrderService().confirm(8, "bob")
a real email goes to bob: order 8 is confirmed
Define a Notifier interface in the domain package, let the email class implement it in the infrastructure, and give the service the notifier in its constructor.
More types and packages. Each separated interface adds an interface, and the code that creates the implementation must be somewhere. For a dependency that does not break a rule of the layers, this is extra work.
The interface must stay stable. Each change of the interface changes all its implementations.
When not to use it
When there is one implementation and no rule to break. If the client may depend on the implementation and the tests do not need a test double, call the class directly.
When the interface only copies one class. An interface with the same methods as its only implementation, in the same package as that class, adds a type and separates nothing.
Variants and related patterns
The interface in the client package. The Go code review guide gives this rule: "Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values."3
Service providers. In Java, "A service is a well-known interface or class for which zero, one, or many service providers exist."4 ServiceLoader finds the implementations at run time, and "Application code refers only to the service, not to service providers".4
Related principles and patterns. The pattern is a way to follow the dependency-inversion-principle and to Program to an interface, not an implementation. A Gateway behind a separated interface can be replaced by a Service stub in tests. A Service locator or Dependency injection gives the client the implementation.
Known uses
- Go programs define small interfaces in the package that uses them.3
- The Java
ServiceLoaderlocates and loads the providers of a service interface that are deployed in the run time environment.4
References
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Separated Interface, pattern summary
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 18, Base Patterns, Separated Interface
- Go Wiki, Go Code Review Comments, Interfaces
- Java SE 21 API, java.util.ServiceLoader, class description
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag VFYRRQ Edit this page History Report an error Markdown