Skip to lesson

Swapping implementations behind an interface

Testing the order rules needs MySQL running with the right rows, so tests are slow and fail on other laptops. If the service only knew an interface, a Map could stand in for the database.

An InMemoryProductDao built on a Map

A fake is a simple working stand-in for a real dependency, such as a DAO that keeps its rows in a Map instead of MySQL.

An in-memory DAO implements the same interface as the JDBC one. Example 1 saves three products in one and runs a service on it.

Example 1 · An in-memory ProductDao and a service that uses it

InMemoryDaoDemo.javaJava
import java.math.BigDecimal;import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.TreeMap;
record Product(int id, String name, BigDecimal price, int stock, boolean active) {}
record NewProduct(String name, BigDecimal price, int stock) {}
interface ProductDao {    Optional<Product> findById(int id);
    List<Product> findActive(int page, int size);
    Product save(NewProduct p);}
class InMemoryProductDao implements ProductDao {    private final Map<Integer, Product> rows = new TreeMap<>();    private int nextId = 1;
    @Override    public Optional<Product> findById(int id) {        return Optional.ofNullable(rows.get(id));    }
    @Override    public List<Product> findActive(int page, int size) {        return rows.values().stream()                .filter(Product::active)                .sorted(Comparator.comparing(Product::name, String.CASE_INSENSITIVE_ORDER)                        .thenComparingInt(Product::id))                .skip((long) (page - 1) * size)                .limit(size)                .toList();    }
    @Override    public Product save(NewProduct p) {        Product saved = new Product(nextId++, p.name(), p.price(), p.stock(), true);        rows.put(saved.id(), saved);        return saved;    }}
class ProductService {    private final ProductDao dao;
    ProductService(ProductDao dao) {        this.dao = dao;    }
    String describe(int id) {        return dao.findById(id).map(p -> p.name() + " at Rs " + p.price()).orElse("No product " + id);    }}
public class InMemoryDaoDemo {    public static void main(String[] args) {        InMemoryProductDao dao = new InMemoryProductDao();        dao.save(new NewProduct("Clean Code", new BigDecimal("499.00"), 30));        dao.save(new NewProduct("boAt Airdopes 141", new BigDecimal("1299.00"), 120));        dao.save(new NewProduct("Atomic Habits", new BigDecimal("399.00"), 50));
        System.out.println(dao.findActive(1, 2));        System.out.println(dao.findActive(2, 2));
        ProductService service = new ProductService(dao);        System.out.println(service.describe(2));        System.out.println(service.describe(9));    }}
Output
[Product[id=3, name=Atomic Habits, price=399.00, stock=50, active=true], Product[id=2, name=boAt Airdopes 141, price=1299.00, stock=120, active=true]]
[Product[id=1, name=Clean Code, price=499.00, stock=30, active=true]]
boAt Airdopes 141 at Rs 1299.00
No product 9

What this code does

  • save gives ids 1, 2, 3 like AUTO_INCREMENT, and findActive sorts names ignoring case and pages with skip/limit, just like ORDER BY name, product_id LIMIT ? OFFSET ? on MySQL.
  • ProductService only knows ProductDao. Given the in-memory DAO it works exactly as it would with MySQL, with no connection at all.

A fake must keep the interface's promises, not just compile: findById returns Optional.empty() for a missing id, save hands out the next id, and findActive returns pages in the same order as MySQL, including the case-insensitive sort by name. A fake that behaves differently makes tests pass that would fail on the real database.

Find the bug

Find the fake bug

A fake must keep the promises of the interface. Tap the wrong line.

findById for a missing id.

Round 1 of 2
In the ShopLite project the in-memory DAOs live in src/test/java, so they are never packaged into the app.

Running the same service with JDBC or in memory

Swapping an implementation means passing a different class that implements the same interface, so the code that uses it does not change.

ProductService takes a ProductDao and a CategoryDao in its constructor, so the wiring code chooses new JdbcProductDao(tx) or new InMemoryProductDao(). Example 2 runs the same service both ways.

BuyService depends only on the ProductDao interface. JdbcProductDao implements it with SQL on MySQL, InMemoryProductDao with a Map for tests. Either class can be plugged in without changing the service.

Example 2 · src/test/java/com/shoplite/app/SwapDemo.java

Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database (test classpath, for the in-memory DAOs)

SwapDemo.javaJava
package com.shoplite.app;
import com.shoplite.config.ConnectionFactory;import com.shoplite.config.DatabaseConfig;import com.shoplite.dao.CategoryDao;import com.shoplite.dao.InMemoryCategoryDao;import com.shoplite.dao.InMemoryProductDao;import com.shoplite.dao.JdbcCategoryDao;import com.shoplite.dao.JdbcProductDao;import com.shoplite.dao.JdbcTransactionManager;import com.shoplite.dao.ProductDao;import com.shoplite.model.NewProduct;import com.shoplite.model.Product;import com.shoplite.service.ProductService;
import java.math.BigDecimal;
/** The same ProductService, first on MySQL, then on Maps. Only the wiring differs. */public class SwapDemo {
    public static void main(String[] args) {        JdbcTransactionManager tx = new JdbcTransactionManager(new ConnectionFactory(DatabaseConfig.load()));        show("JDBC", new ProductService(new JdbcProductDao(tx), new JdbcCategoryDao(tx)));
        InMemoryCategoryDao categories = new InMemoryCategoryDao();        categories.add(5, "Books");        ProductDao memory = new InMemoryProductDao();        ProductService inMemory = new ProductService(memory, categories);        inMemory.addProduct(new NewProduct("BK-GODAN", "Godan", 5, new BigDecimal("250.00"), 12));        inMemory.addProduct(new NewProduct("BK-GITA", "Gitanjali", 5, new BigDecimal("180.00"), 7));        show("In-memory", inMemory);    }
    private static void show(String label, ProductService service) {        System.out.println(label + ":");        for (Product p : service.listProducts(1, 3).items()) {            System.out.println("  " + p.name() + " - Rs " + p.price());        }    }}
Output (freshly loaded database)
JDBC:
  Atomic Habits - Rs 399.00
  boAt Airdopes 141 - Rs 1299.00
  Clean Code - Rs 499.00
In-memory:
  Gitanjali - Rs 180.00
  Godan - Rs 250.00

What this code does

  • The same ProductService class runs twice. The only difference is which DAOs are passed to its constructor.
  • With JDBC the first page comes from MySQL; in memory it comes from two books saved through the service itself, so addProduct's validation ran on them too.

This is the payoff of constructor injection plus interfaces: not one line of ProductService changes, and only the place that creates objects knows the concrete classes.

JUnit 5 tests of a service with a fake DAO

JUnit 5 is the standard Java test library: a test is a method marked @Test, and assertEquals and assertThrows check its results.

OrderServiceTest builds OrderService with in-memory DAOs and a DirectTransactionManager that just runs the work. Example 3 runs it, and Example 4 shows a one-character bug being caught.

Example 3 · src/test/java/com/shoplite/service/OrderServiceTest.java

Runs in: the shoplite-console project (JUnit 5, no database needed)

Java
package com.shoplite.service;
import com.shoplite.dao.DirectTransactionManager;import com.shoplite.dao.InMemoryCustomerDao;import com.shoplite.dao.InMemoryOrderDao;import com.shoplite.dao.InMemoryProductDao;import com.shoplite.model.NewCustomer;import com.shoplite.model.NewProduct;import com.shoplite.model.OrderLine;import com.shoplite.model.PlacedOrder;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;
import java.math.BigDecimal;import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertThrows;
class OrderServiceTest {    private InMemoryProductDao products;    private InMemoryOrderDao orders;    private OrderService service;
    @BeforeEach    void setUp() {        products = new InMemoryProductDao();        InMemoryCustomerDao customers = new InMemoryCustomerDao();        orders = new InMemoryOrderDao();        customers.save(new NewCustomer("Asha Rao", "asha.rao@example.com", null));   // id 1        customers.addAddress(1, 1);        products.save(new NewProduct("MOB-RN13", "Redmi Note 13 5G", 2, new BigDecimal("17999.00"), 40)); // id 1        products.save(new NewProduct("ACC-AD141", "boAt Airdopes 141", 4, new BigDecimal("1299.00"), 1)); // id 2        service = new OrderService(new DirectTransactionManager(), customers, products, orders);    }
    @Test    void placesOrderReducesStockAndAddsUpTotal() {        PlacedOrder placed = service.placeOrder(1, 1, List.of(new OrderLine(1, 2), new OrderLine(2, 1)));
        assertEquals(new BigDecimal("37297.00"), placed.total());        assertEquals(38, products.findById(1).orElseThrow().stock());        assertEquals(0, products.findById(2).orElseThrow().stock());    }
    @Test    void outOfStockChangesNothing() {        List<OrderLine> lines = List.of(new OrderLine(1, 1), new OrderLine(2, 3));
        OutOfStockException e = assertThrows(OutOfStockException.class, () -> service.placeOrder(1, 1, lines));
        assertEquals("Only 1 left of boAt Airdopes 141 (you asked for 3)", e.getMessage());        assertEquals(40, products.findById(1).orElseThrow().stock());        assertEquals(0, orders.count());    }
    @Test    void rejectsQuantityAboveLimit() {        List<OrderLine> lines = List.of(new OrderLine(1, 6));
        assertThrows(InvalidInputException.class, () -> service.placeOrder(1, 1, lines));    }
    @Test    void rejectsAddressOfAnotherCustomer() {        List<OrderLine> lines = List.of(new OrderLine(1, 1));
        assertThrows(InvalidInputException.class, () -> service.placeOrder(1, 9, lines));    }
    @Test    void unknownProductIsReported() {        List<OrderLine> lines = List.of(new OrderLine(99, 1));
        ProductNotFoundException e = assertThrows(ProductNotFoundException.class,                () -> service.placeOrder(1, 1, lines));        assertEquals("No product with id 99", e.getMessage());    }}
Sample output (mvn test)
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.shoplite.service.CustomerServiceTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.146 s -- in com.shoplite.service.CustomerServiceTest
[INFO] Running com.shoplite.service.OrderServiceTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.097 s -- in com.shoplite.service.OrderServiceTest
[INFO] Running com.shoplite.service.ProductServiceTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.061 s -- in com.shoplite.service.ProductServiceTest
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 11, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  12.144 s

What this code does

  • @BeforeEach builds fresh fakes for every test: one customer with address 1, and two products, the second with only 1 in stock. Tests never share data, so their order does not matter.
  • outOfStockChangesNothing checks the message and that nothing changed: stock of product 1 is still 40 and no order was created. That is the "check everything before writing" rule.
  • All 11 tests of the three service classes ran in well under a second, with MySQL not even needed.

Example 4 · A one-character bug, caught by the tests

Runs in: the shoplite-console project, after changing < to <= in the stock check of OrderService

Terminal
# OrderService, broken on purpose:#   if (p.stock() <= line.quantity()) {mvn test
Sample output (trimmed to the test results)
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.shoplite.service.CustomerServiceTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.147 s -- in com.shoplite.service.CustomerServiceTest
[INFO] Running com.shoplite.service.OrderServiceTest
[ERROR] Tests run: 5, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.141 s <<< FAILURE! -- in com.shoplite.service.OrderServiceTest
[ERROR] com.shoplite.service.OrderServiceTest.placesOrderReducesStockAndAddsUpTotal -- Time elapsed: 0.016 s <<< ERROR!
com.shoplite.service.OutOfStockException: Only 1 left of boAt Airdopes 141 (you asked for 1)
	at com.shoplite.service.OrderService.lambda$placeOrder$2(OrderService.java:53)
	at com.shoplite.dao.DirectTransactionManager.inTransaction(DirectTransactionManager.java:10)
	at com.shoplite.service.OrderService.placeOrder(OrderService.java:37)
	at com.shoplite.service.OrderServiceTest.placesOrderReducesStockAndAddsUpTotal(OrderServiceTest.java:39)

[INFO] Running com.shoplite.service.ProductServiceTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.033 s -- in com.shoplite.service.ProductServiceTest
[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR]   OrderServiceTest.placesOrderReducesStockAndAddsUpTotal:39 » OutOfStock Only 1 left of boAt Airdopes 141 (you asked for 1)
[INFO]
[ERROR] Tests run: 11, Failures: 0, Errors: 1, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE

What this code does

  • With <=, buying the last unit is refused: 1 left, 1 asked, yet "Only 1 left". The happy-path test that buys the last pair of earbuds fails at once and names the exact test and line.
  • Without fakes this bug would surface only when a real customer tried to buy the last unit. Change <= back to < and the build is green again.

@BeforeEach prepares fresh objects before every test, and Maven runs every test class in src/test/java with mvn test. The order rules are tested in a fraction of a second, on any laptop or build server, without MySQL.

Fakes test the rules, not the SQL. The JDBC DAOs still need tests against a real database (integration tests), which Section 16 adds.

Why depending on interfaces makes code easy to change

A decorator is a class that implements an interface by wrapping another implementation of it, and adds behaviour such as caching, logging or timing around each call.

Example 5 wraps a slow DAO in a CachingProductDao. The service gets the cache without being changed.

Example 5 · A caching decorator around any ProductDao

DecoratorDemo.javaJava
import java.util.HashMap;import java.util.Map;import java.util.Optional;
record Product(int id, String name) {}
interface ProductDao {    Optional<Product> findById(int id);}
// Pretends to be the JDBC DAO: every call is a slow database queryclass SlowProductDao implements ProductDao {    int queries = 0;
    @Override    public Optional<Product> findById(int id) {        queries++;        return id == 11 ? Optional.of(new Product(11, "Atomic Habits")) : Optional.empty();    }}
// Decorator: same interface, wraps another DAO, remembers answersclass CachingProductDao implements ProductDao {    private final ProductDao inner;    private final Map<Integer, Optional<Product>> cache = new HashMap<>();
    CachingProductDao(ProductDao inner) {        this.inner = inner;    }
    @Override    public Optional<Product> findById(int id) {        return cache.computeIfAbsent(id, inner::findById);    }}
class ProductService {    private final ProductDao dao;
    ProductService(ProductDao dao) {        this.dao = dao;    }
    String title(int id) {        return dao.findById(id).map(Product::name).orElse("unknown");    }}
public class DecoratorDemo {    public static void main(String[] args) {        SlowProductDao slow = new SlowProductDao();        ProductService plain = new ProductService(slow);        for (int i = 0; i < 3; i++) {            plain.title(11);        }        System.out.println("Without cache: " + slow.queries + " queries");
        SlowProductDao slow2 = new SlowProductDao();        ProductService cached = new ProductService(new CachingProductDao(slow2));        for (int i = 0; i < 3; i++) {            cached.title(11);        }        System.out.println("With cache:    " + slow2.queries + " query, title " + cached.title(11));    }}
Output
Without cache: 3 queries
With cache:    1 query, title Atomic Habits

What this code does

  • CachingProductDao is itself a ProductDao, so ProductService accepts it without any change. Three calls cost one query instead of three.
  • A real cache must also forget entries when a product changes, or it serves stale prices. The point here is the shape: new behaviour added by wrapping, not by editing the service or the JDBC DAO.

Code that depends on an interface depends only on what is done, not how, so you change or add behaviour by writing a new class instead of editing old ones. The same idea later lets ShopLite swap its connection source for a pool and its DAOs for Spring repositories.

Predict the output

How many queries?

Count the queries that reach MySQL.

Round 1 of 2

The service uses the caching decorator.

ProductDao dao = new CachingProductDao(jdbcDao);
dao.findById(1);
dao.findById(1);
dao.findById(1);

How this prepares for Spring repositories

A repository is Spring's name for a DAO. With Spring Data JPA you write only the interface, and Spring generates the implementation at startup.

The code below previews Section 16: the repository is an interface, and the service receives it through its constructor, like every ShopLite service.

ProductRepository.javaJava
// Section 16 preview: Spring Data generates the implementation of this interfacepublic interface ProductRepository extends JpaRepository<Product, Integer> {    Page<Product> findByActiveTrue(Pageable pageable);}
// The service looks just like ShopLite's: rules, plus a dependency from the constructor@Servicepublic class ProductService {    private final ProductRepository products;
    public ProductService(ProductRepository products) {        this.products = products;    }}

Section 15 writes repository classes with Spring's JdbcClient, the same idea as ShopLite's JDBC DAOs. What stays the same is everything this module built: services hold the rules, receive repositories through the constructor and depend on interfaces. Spring does the wiring that Main does today.

Next step

Check your understanding

12 quick questions