依赖规则详解
掌握依赖规则这一基本原则:依赖只能向内流动,从而确保核心业务逻辑保持隔离。
依赖规则详解 是 CoddyKit 上的免费 Clean Architecture & Design Patterns in Practice 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Clean Architecture & Design Patterns in Practice 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Clean Architecture & Design Patterns in Practice 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
The Core of Clean Architecture
Welcome to our lesson on the Dependency Rule! This principle is the cornerstone of Clean Architecture, ensuring your core business logic remains isolated and independent.
It's all about directing the flow of dependencies in your application in a very specific way.
Dependencies Flow Inwards
The fundamental idea is simple: dependencies can only flow inwards. This means outer layers of your architecture must depend on inner layers, but inner layers must never depend on outer layers.
Think of it as a one-way street, always leading towards the center of your application's logic.
Visualizing the Rule
Recall the concentric circles of Clean Architecture (Entities, Use Cases, Interface Adapters, Frameworks/Drivers). The Dependency Rule dictates that code in an outer circle can depend on code in an inner circle, but never the other way around.
- Inner layers: Core business rules, independent.
- Outer layers: UI, databases, web frameworks, external services.
Why This Rule Matters
Strictly following the Dependency Rule brings significant benefits:
- Isolation: Your core business logic is protected from changes in UI, databases, or frameworks.
- Testability: You can test your core logic without needing to set up a database or a web server.
- Flexibility: You can swap out external components (e.g., change from SQL to NoSQL, or from one web framework to another) with minimal impact on your core.
Outer Layer Calling Inward
This is the natural and allowed flow. An outer layer, like a web controller, depends on an inner layer, like a Use Case, to perform an action. The controller knows about the use case.
Try running this example:
class CreateUserUseCase {
public void execute(String username) {
System.out.println("Logic to create user: " + username);
}
}
// Outer layer (e.g., Web Controller)
class UserController {
private final CreateUserUseCase createUserUseCase;
public UserController(CreateUserUseCase useCase) {
this.createUserUseCase = useCase;
}
public String register(String username) {
createUserUseCase.execute(username);
return "User registration initiated for " + username;
}
}
public class Main {
public static void main(String[] args) {
CreateUserUseCase useCase = new CreateUserUseCase();
UserController controller = new UserController(useCase);
System.out.println(controller.register("Alice"));
}
}Inner Layer Independence
Now, what if our CreateUserUseCase (inner layer) needs to send a success message back to the UserController (outer layer)?
It cannot directly call a method on the UserController. That would mean the inner layer depends on the outer layer, breaking the Dependency Rule!
Inverting the Dependency
To solve this, we use Dependency Inversion. The inner layer (Use Case) defines an interface (often called a 'Port' or 'Output Port') that it expects to communicate through.
The outer layer (Controller/Presenter) then implements this interface and provides itself to the inner layer. This reverses the flow of dependency at compile time.
Code: Inverted Dependency
Observe how the CreateUserUseCase now depends only on its own interface, UserOutputPort. The UserController implements this port, allowing the Use Case to 'talk back' without knowing the specific UI details.
Try running this example:
// 1. Inner layer defines its 'output port' (interface)
interface UserOutputPort {
void presentUserCreationResult(String message);
}
// 2. Inner layer (Use Case) depends on its own interface
class CreateUserUseCase {
private final UserOutputPort outputPort;
public CreateUserUseCase(UserOutputPort outputPort) {
this.outputPort = outputPort;
}
public void execute(String username) {
// Simulate user creation logic
System.out.println("Processing creation for: " + username);
outputPort.presentUserCreationResult("User '" + username + "' created!");
}
}
// 3. Outer layer (e.g., Web Controller) implements the 'port'
class UserController implements UserOutputPort {
private final CreateUserUseCase createUserUseCase;
public UserController() {
// Controller provides itself as the output port
this.createUserUseCase = new CreateUserUseCase(this);
}
public void registerUser(String username) {
createUserUseCase.execute(username);
}
@Override
public void presentUserCreationResult(String message) {
System.out.println("UI Update: " + message);
}
}
public class Main {
public static void main(String[] args) {
UserController controller = new UserController();
controller.registerUser("Bob");
}
}Consequences of Breaking the Rule
Violating the Dependency Rule leads to a fragile and rigid architecture:
- Tight Coupling: Your core logic becomes tied to external details (UI, DB).
- Difficult Testing: Testing business rules requires setting up external components.
- Reduced Flexibility: Changing frameworks or databases becomes a massive undertaking.
- Leaky Abstractions: Inner layers expose knowledge of outer layers, making the system harder to understand and maintain.
Quick Check
The Dependency Rule is crucial for maintaining a clean and flexible architecture. Let's test your understanding of how dependencies should flow.
Recap: The Dependency Rule
You've learned that the Dependency Rule is the core principle of Clean Architecture, dictating that dependencies must always flow inwards, from outer layers to inner layers.
- It protects your core business logic.
- It enhances testability and flexibility.
- Dependency Inversion (using interfaces) is key to allowing inner layers to communicate outwards without direct dependencies.
Mastering this rule is essential for building robust and maintainable software systems!
常见问题解答
「依赖规则详解」课时是免费的吗?
是的 — 「依赖规则详解」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Clean Architecture & Design Patterns in Practice 课程的其余内容,请升级到 CoddyKit PRO。 Clean Architecture & Design Patterns in Practice 课程共包含 4 节课。
「依赖规则详解」这节课中我会学到什么?
掌握依赖规则这一基本原则:依赖只能向内流动,从而确保核心业务逻辑保持隔离。 你通过在浏览器中直接运行的动手代码来练习 Clean Architecture & Design Patterns in Practice,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Clean Architecture & Design Patterns in Practice 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Clean Architecture & Design Patterns in Practice 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「依赖规则详解」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Clean Architecture & Design Patterns in Practice 课中编写并运行代码吗?
能。每节 Clean Architecture & Design Patterns in Practice 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。