Why Following the Law of Demeter Can Simplify Our Flutter Code
Shahanaj Parvin
9+ Years in Mobile App Development | 6+ Years in Flutter | Agile & Jira Proficient
When developing Flutter applications, we often focus on building visually stunning UIs and delivering great performance. But maintaining a clean, maintainable codebase is just as crucial. One key principle that can help you achieve this is the Law of Demeter (LoD), also known as the principle of least knowledge.
What Is the Law of Demeter?
In simple terms, the Law of Demeter states:
An object should only communicate with its immediate collaborators.
In practical terms, this means avoiding long chains of method calls like:
obj.getA().getB().doSomething();
This kind of code creates tightly coupled systems that are hard to maintain and test. Let’s dive into a real-world Flutter example to understand this better.
Flutter Example: E-commerce App
Imagine you're building a product catalog for an e-commerce app. Each product has a stock status that determines whether it's available for purchase.
The Problem
Here’s an example of code that violates the Law of Demeter:
bool isProductInStock(Product product) {
return product.getStock().isInStock(); // Violates LoD
}
This code depends on multiple layers of objects (Product -> Stock -> isInStock). If the Stock class changes, this code will break, making it fragile and difficult to maintain.
The Solution
Instead, the Product class should handle the responsibility of determining its stock status. Let’s refactor:
class Product {
final Stock stock;
Product(this.stock);
bool isInStock() => stock.quantity > 0; // Encapsulates stock logic
}
Now, the UI code becomes cleaner:
bool isProductInStock(Product product) {
return product.isInStock(); // Follows LoD
}
Why This Matters