4 – The Information Hiding Principle: How encapsulation prevents assumptions that cause code to break

Assumptions about the internal implementation of old code make new code brittle and prone to breaking

We have seen how, according to the Law of Demeter, a type with too many relationships to other types is a recognizable code smell.

However, the Law of Demeter has far bigger consequences. Modules do not break only when they have too many relationships, but also when they know too much about each other.

As a developer, knowing precisely how your code works can be a double-edged sword. If you are not careful, you can introduce coupling in your code in subtle ways that are hard to spot.

When you write new code that interacts with existing code, it is easy to subconsciously bake your assumptions about old code into the new code you are writing.

However, at some point, you will forget about those assumptions. Some day, you might change the internal implementation of a module and inadvertently introduce bugs in code where previous assumptions no longer hold.

Assumptions are also tricky to spot because they are implicit and cannot be checked by the compiler. While the compiler might be happy with your changes, the absence of compilation errors does not guarantee the absence of bugs.

Prevent coupling by encapsulating code that is likely to change, hiding it from the rest of the codebase

The solution is then to reduce the number of assumptions in our code. And since making assumptions is a natural, subconscious instinct, we have to actively fight against it.

We do so through encapsulation, i.e., by hiding code in a module and restricting direct access to it. Encapsulation is often used interchangeably with the Information Hiding principle, which follows from the Law of Demeter.

The Information Hiding principle

Design decisions in a module that are most likely to change should be encapsulated behind a stable interface, protecting other parts of the program from extensive modification if the design decision is changed.

There are several code smells, some with funny names, that can indicate a lack of information hiding and a need for more encapsulation.

  • Primitive obsession, i.e., code that repeats the same operations on primitive types like numbers and strings.
  • Data clumps, i.e., identical groups of variables repeated across different parts of the code base.
  • Plain data types, i.e., structures or classes that only contain stored properties.
  • Feature envy, i.e., a method accesses the data of another type more than its own data.
  • Duplicated code: code fragments across the codebase that look almost identical.

These all revolve around the same concept: the code is misplaced and should instead be encapsulated in a module (a type or a method) and exposed only through an interface that provides the relevant details.

Do this: Move code accessing the internal implementation of a type into the type itself

It should no longer come as a surprise that SwiftUI views are the modules most likely to violate the Information Hiding principle.

As we have seen, views accumulate several concerns. One common mistake is embedding domain business logic in views, i.e., the parts of the program that encode the real-world business rules that determine how data is organized.

The plain data types code smell is the one I see most often. It is typical in SwiftUI apps to have code in views that acts on or performs calculations using values stored in the properties of plain Swift structures or objects.

For example, a view in our budgeting app showing the total balance across all budget categories could include code that performs the entire calculation.

struct CategoriesView: View {
	@Query(sort: \Category.name) private var categories: [Category]

	var body: some View {
		List {
			Balance(amount: balance)
			// ...
		}
		// ...
	}

	var balance: Decimal {
		var balance: Decimal = 0
		for category in categories {
			for transaction in category.transactions {
				balance += (transaction.type == .expense ? -1 : 1) * transaction.amount
			}
		}
		return balance
	}
}

Code smells often come together since they are all consequences of violating the Law of Demeter.

Notice how the plain data type code smell in the Category and Transaction types causes the inappropriate intimacy code smell in the CategoriesView.

Changing the internal implementation of the Category and Transaction data types will break CategoriesView and any other view that peeks too deeply into details it should not know.

Some of these breaking changes will be caught by the compiler, but others might go undetected and introduce bugs that slip through to your users.

The solution is to move such code into the plain types, hiding the implementation from the CategoriesView. Swift extensions also help with refactoring, allowing us to add code to types we don’t own, like the Array type.

@Model final class Transaction {
	var type: TransactionType
	var amount: Decimal
	var category: Category

	enum TransactionType: Codable {
		case income, expense
	}

	// ...

	var signedAmount: Decimal {
		(type == .expense ? -1 : 1) * amount
	}
}

extension [Transaction] {
	var balance: Decimal {
		var balance: Decimal = 0
		for transaction in self {
			balance += transaction.signedAmount
		}
		return balance
	}
}

@Model final class Category {
	// ...

	var balance: Decimal { transactions.balance }
}

extension [Category] {
	var balance: Decimal {
		var balance: Decimal = 0
		for category in self {
			balance += category.balance
		}
		return balance
	}
}

struct CategoriesView: View {
	@Query(sort: \Category.name) private var categories: [Category]

	var body: some View {
		List {
			Balance(amount: categories.balance)
			// ...
		}
		// ...
	}
}

Through this refactoring, we also gained something more.

We can now unit test the code calculating the balance of transactions and categories, which was not possible when the code was in the view due to how SwiftUI works.

@Test func balance() async throws {
	#expect(Category.fitness.balance == -485.87)
}
Back to: The SwiftUI Architecture Audit > Lessons

Leave a Comment