Encapsulate What Varies

June 15, 2020 1 minute read

The only constant thing about requirements is that they change. As engineers we need to translate the complicated patterns of the real world into the technological one. Software should be built in a way that allows it to adapt to change.

Encapsulating what varies is a technique that helps us handle frequently changing details. Code tends to get tangled when it is continuously modified due to new features or requirements. By isolating the parts which are prone to change we limit the surface area that will be affected by a shift in requirements.

Ideally, a single change in requirements should leat to a single change in the code. So the details should be put under a class, module or component that is going to centralize the varying logic.

// ❌ This is hard to understand and subject to change.
// We may need to check if a book is reserved.
function checkoutBook(customer, book) {
  if (
    customer &&
    customer.fine <= 0.0 &&
    customer.card &&
    customer.card.expiration === null &&
    book &&
    !book.isCheckedOut
  ) {
    customer.books.push(book)
    book.isCheckedOut = true
  }
  return customer
}

// ✅ This is easy to read and won't change even if the checkout requirements vary.
function checkoutBook(customer, book) {
  if (customer.canCheckout(book)) {
    customer.checkout(book)
  }

  return customer
}

Logic may vary for different reasons. It may be due to a shift in business direction. Perhaps a new market research has given us insights on the users’s behaviour. It may be due to regulatory requirements like a change in how a tax is calculated.

Encapsulating the details makes it easier to reason about the domain as well. As engineers we need to be familiar with the business we’re supporting. The more complicated the domain is, the longer it will take us to fully understand it.

Not all details vary. But the things that vary are usually details. By following this technique we also make the business easier to grasp by developers as a side effect.

Tao of React

Learn proven practices about React application architecture, component design, testing and performance.