Depend on the interface, hand the object in
After this: Give an order service its storage from outside, behind an interface, and use an in-memory one in a test.
On this page · 6 sections · 3 checks
An online shop has an OrderService that takes orders and saves each one. The first version saves into a file. Then the team wants to test the service without writing any files, and later to save into a database. In "Interfaces and polymorphism in design" a checkout received its payment method from outside. This lesson turns that habit into the last rule of SOLID.
A service that builds its own storage
class FileStorage: def __init__(self, path): self.path = path self.lines = [] # stands in for the file on disk
def save(self, item): self.lines.append(item)
class OrderService: def __init__(self): self.storage = FileStorage("orders.txt") self.placed = 0
def place(self, item): self.storage.save(item) self.placed += 1 return f"order {self.placed}: {item}"
service = OrderService()print(service.place("pen"))print(service.place("book"))order 1: pen order 2: book
import java.util.ArrayList;import java.util.List;
class FileStorage { private String path; private List<String> lines = new ArrayList<>(); // stands in for the file on disk
FileStorage(String path) { this.path = path; }
void save(String item) { lines.add(item); }}
class OrderService { private FileStorage storage; private int placed = 0;
OrderService() { this.storage = new FileStorage("orders.txt"); }
String place(String item) { storage.save(item); placed += 1; return "order " + placed + ": " + item; }}
public class Main { public static void main(String[] args) { OrderService service = new OrderService(); System.out.println(service.place("pen")); System.out.println(service.place("book")); }}order 1: pen order 2: book
Here FileStorage keeps the lines in a list as a stand-in, so the program runs anywhere; a real one would write them to the file.
- OrderService is made of 1 FileStorage (composition)
Look at the constructor of OrderService. It creates FileStorage("orders.txt") itself. That one line ties the service to one kind of storage and one file name:
- A test of
placehas to use the file storage, because there is no way to give the service another. - Moving to a database means editing
OrderService, a class whose job is orders, not storage. - The filled diamond in the diagram says the same: the service makes its storage and owns it.
Depend on the interface
A class that another class needs in order to work is called its . The rule has two parts:
- A class that makes the decisions, such as how orders are placed, should not depend on a class that does low-level work, such as writing a file. Both should depend on an interface between them.
- The interface is shaped by what the decision-maker needs, a
savemethod, not by the details of files.
This is the , the D of SOLID. Inversion means turning round: the arrow that went from the service to the file class now goes from the file class up to the interface.
Hand the object in
The way to write it is the habit from "Interfaces and polymorphism in design": hand the object in, do not create it inside. Its name is .
- OrderService is linked to 1 Storage
- InMemoryStorage implements Storage
- FileStorage implements Storage
from abc import ABC, abstractmethod
class Storage(ABC): @abstractmethod def save(self, item): pass
class FileStorage(Storage): def __init__(self, path): self.path = path self.lines = [] # stands in for the file on disk
def save(self, item): self.lines.append(item)
class InMemoryStorage(Storage): def __init__(self): self.items = []
def save(self, item): self.items.append(item)
def count(self): return len(self.items)
def last(self): return self.items[-1]
class OrderService: def __init__(self, storage): self.storage = storage self.placed = 0
def place(self, item): self.storage.save(item) self.placed += 1 return f"order {self.placed}: {item}"
store = InMemoryStorage()service = OrderService(store)print(service.place("pen"))print(service.place("book"))print(store.count(), store.last())print(OrderService(FileStorage("orders.txt")).place("lamp"))order 1: pen order 2: book 2 book order 1: lamp
import java.util.ArrayList;import java.util.List;
interface Storage { void save(String item);}
class FileStorage implements Storage { private String path; private List<String> lines = new ArrayList<>(); // stands in for the file on disk
FileStorage(String path) { this.path = path; }
public void save(String item) { lines.add(item); }}
class InMemoryStorage implements Storage { private List<String> items = new ArrayList<>();
public void save(String item) { items.add(item); }
int count() { return items.size(); }
String last() { return items.get(items.size() - 1); }}
class OrderService { private Storage storage; private int placed = 0;
OrderService(Storage storage) { this.storage = storage; }
String place(String item) { storage.save(item); placed += 1; return "order " + placed + ": " + item; }}
public class Main { public static void main(String[] args) { InMemoryStorage store = new InMemoryStorage(); OrderService service = new OrderService(store); System.out.println(service.place("pen")); System.out.println(service.place("book")); System.out.println(store.count() + " " + store.last()); System.out.println(new OrderService(new FileStorage("orders.txt")).place("lamp")); }}order 1: pen order 2: book 2 book order 1: lamp
Walk through it:
Storageis the interface, with one method:save.OrderServicereceives aStoragein its constructor and keeps it in a field. It never namesFileStorageorInMemoryStorage.InMemoryStoragekeeps the items in a list, withcountandlastfor checking. The program places a pen and a book, and then the storage holds 2 items, the last one a book:2 book.- The same
OrderServiceclass works with aFileStoragetoo, and its first order printsorder 1: lamp. Nothing in the service changed.
A test can now hand in an InMemoryStorage and then ask it what was saved. A database storage would be one more class that implements Storage.
Run it
Write a PrintStorage whose save prints the item, and hand one to a new OrderService. The service does not change.
Check yourself
Which constructor for OrderService follows the dependency inversion principle?
Why can a test now use InMemoryStorage without editing OrderService?
Two services are handed the same storage object. What does this print?
from abc import ABC, abstractmethod
class Storage(ABC): @abstractmethod def save(self, item): pass
class FileStorage(Storage): def __init__(self, path): self.path = path self.lines = [] # stands in for the file on disk
def save(self, item): self.lines.append(item)
class InMemoryStorage(Storage): def __init__(self): self.items = []
def save(self, item): self.items.append(item)
def count(self): return len(self.items)
def last(self): return self.items[-1]
class OrderService: def __init__(self, storage): self.storage = storage self.placed = 0
def place(self, item): self.storage.save(item) self.placed += 1 return f"order {self.placed}: {item}"
store = InMemoryStorage()a = OrderService(store)b = OrderService(store)a.place("pen")b.place("cup")print(b.place("ink"))print(store.count(), store.last())import java.util.ArrayList;import java.util.List;
interface Storage { void save(String item);}
class FileStorage implements Storage { private String path; private List<String> lines = new ArrayList<>(); // stands in for the file on disk
FileStorage(String path) { this.path = path; }
public void save(String item) { lines.add(item); }}
class InMemoryStorage implements Storage { private List<String> items = new ArrayList<>();
public void save(String item) { items.add(item); }
int count() { return items.size(); }
String last() { return items.get(items.size() - 1); }}
class OrderService { private Storage storage; private int placed = 0;
OrderService(Storage storage) { this.storage = storage; }
String place(String item) { storage.save(item); placed += 1; return "order " + placed + ": " + item; }}
public class Main { public static void main(String[] args) { InMemoryStorage store = new InMemoryStorage(); OrderService a = new OrderService(store); OrderService b = new OrderService(store); a.place("pen"); b.place("cup"); System.out.println(b.place("ink")); System.out.println(store.count() + " " + store.last()); }}When not to bother
- Say the dependency inversion principle: the class that makes decisions and the class that does low-level work both depend on an interface between them.
- Spot the sign: a class that creates its own file, database or sender inside its constructor.
- Hand the object in through the constructor (dependency injection), and keep the field's type as the interface.
- Use an in-memory storage to check what a service saved, without a file and without editing the service.