Chapters 15 16:What Is Architecture?Independence_《clean architecture》notes

What Is Architecture?&Independence

      • **Chapter 15: What Is Architecture?**
        • **Key Concepts**:
        • **Code Example: Layered Architecture**:
      • **Chapter 16: Independence**
        • **Key Concepts**:
        • **Code Example: Dependency Inversion & Interfaces**:
      • **Combined Example: Boundaries & Independence**
      • **Key Takeaways**:
      • **Chapters 15 & 16 Overview**
      • **10 Hard Difficulty Multiple-Choice Questions**
      • **Test Code Examples**


Chapter 15: What Is Architecture?

Key Concepts:
  1. Definition: Architecture is the shape of a system defined by components, dependencies, and boundaries that manage complexity and enable evolution.
  2. Core Goals:
    • Manage Complexity: Decouple components to isolate changes.
    • Keep Options Open: Delay decisions (e.g., frameworks, databases) to avoid premature constraints.
    • Support Use Cases: Ensure the system delivers business value.
  3. Layers & Boundaries:
    • Separate high-level policy (business logic) from low-level details (I/O, UI).
    • Use boundaries (interfaces, abstractions) to isolate volatile components.
Code Example: Layered Architecture:
#include <iostream>
#include <string>
#include <vector>// High-level Policy (Business Logic)
class Order {
public:virtual double calculateTotal() const = 0;virtual ~Order() = default;
};// Low-level Detail (Implementation)
class ConcreteOrder : public Order {
private:std::vector<double> items;
public:void addItem(double price) { items.push_back(price); }double calculateTotal() const override {double total = 0;for (auto price : items) total += price;return total;}
};// Client Code (Depends on Abstraction)
void printTotal(const Order& order) {std::cout << "Total: $" << order.calculateTotal() << std::endl;
}int main() {ConcreteOrder order;order.addItem(10.5);order.addItem(20.3);printTotal(order); // Output: Total: $30.8return 0;
}

Explanation:

  • Abstraction: Order is an interface defining business rules.
  • Implementation: ConcreteOrder provides the calculation logic.
  • Dependency Inversion: printTotal depends on the abstract Order, not concrete details.

Chapter 16: Independence

Key Concepts:
  1. Component Independence:
    • Deployability: Components can be deployed separately (e.g., microservices).
    • Developability: Teams work independently on components.
    • Replaceability: Swap implementations without breaking the system.
  2. Decoupling Techniques:
    • Dependency Inversion: Depend on abstractions, not concretions.
    • Interface Segregation: Split interfaces to avoid unnecessary dependencies.
    • Boundary Patterns: Use layers, ports/adapters, or hexagonal architecture.
Code Example: Dependency Inversion & Interfaces:
#include <iostream>
#include <memory>// Abstraction (Port)
class Database {
public:virtual void save(const std::string& data) = 0;virtual ~Database() = default;
};// Low-level Detail (Adapter)
class SQLDatabase : public Database {
public:void save(const std::string& data) override {std::cout << "Saving to SQL: " << data << std::endl;}
};// High-level Policy
class UserService {
private:std::unique_ptr<Database> db;
public:UserService(std::unique_ptr<Database> db) : db(std::move(db)) {}void createUser(const std::string& name) {db->save("User: " + name);}
};int main() {auto sqlDb = std::make_unique<SQLDatabase>();UserService service(std::move(sqlDb));service.createUser("Alice"); // Output: Saving to SQL: User: Alicereturn 0;
}

Explanation:

  • Dependency Inversion: UserService depends on the Database abstraction.
  • Testability: Easily swap SQLDatabase with a MockDatabase for testing.
  • Decoupling: Changes to the database implementation don’t affect UserService.

Combined Example: Boundaries & Independence

#include <iostream>
#include <memory>// Port (Interface)
class PaymentGateway {
public:virtual void pay(double amount) = 0;virtual ~PaymentGateway() = default;
};// Adapter 1: PayPal Implementation
class PayPalGateway : public PaymentGateway {
public:void pay(double amount) override {std::cout << "Paying $" << amount << " via PayPal." << std::endl;}
};// Adapter 2: Stripe Implementation
class StripeGateway : public PaymentGateway {
public:void pay(double amount) override {std::cout << "Paying $" << amount << " via Stripe." << std::endl;}
};// High-level Policy
class OrderService {
private:std::unique_ptr<PaymentGateway> gateway;
public:OrderService(std::unique_ptr<PaymentGateway> gateway) : gateway(std::move(gateway)) {}void processOrder(double amount) {gateway->pay(amount);}
};int main() {// Swap payment gateways without changing OrderService.auto paypal = std::make_unique<PayPalGateway>();OrderService service1(std::move(paypal));service1.processOrder(100.0); // Output: Paying $100 via PayPal.auto stripe = std::make_unique<StripeGateway>();OrderService service2(std::move(stripe));service2.processOrder(200.0); // Output: Paying $200 via Stripe.return 0;
}

Explanation:

  • Boundary: PaymentGateway defines a port for payment processing.
  • Independence: OrderService is decoupled from specific payment providers.
  • Flexibility: New gateways (e.g., BitcoinGateway) can be added without modifying core logic.

Key Takeaways:

  1. Architecture = Managed Dependencies: Use abstractions to isolate volatility.
  2. Delay Decisions: Keep infrastructure (databases, UIs) replaceable.
  3. Test with Mocks: Compile-time polymorphism enables testing without concrete dependencies.

Chapters 15 & 16 Overview

Chapter 15: “What Is Architecture?”

  • Focuses on defining architecture as the structure of components, their relationships, and design principles guiding evolution.
  • Key topics:
    1. Architectural goals: Managing dependencies between components, enabling flexibility, and delaying decisions.
    2. Impact on development phases: Deployment, operation, maintenance, and evolution.
    3. Device independence and avoiding premature commitment to frameworks/databases.

Chapter 16: “Independence”

  • Discusses designing systems to achieve independent components for flexibility and scalability.
  • Key topics:
    1. Horizontal vs. vertical decoupling: Separating use cases, layers (UI, business logic, data).
    2. Delaying decisions: Keeping options open by abstracting volatile components (e.g., databases).
    3. Avoiding duplication while balancing decoupling.

10 Hard Difficulty Multiple-Choice Questions

Question 1
Which are core goals of software architecture according to Chapter 15?
A) Maximize code performance.
B) Delay irreversible decisions.
C) Enforce strict coding standards.
D) Manage dependencies between components.


Question 2
What does “device independence” imply in Clean Architecture?
A) Code must run on all hardware without modification.
B) Business logic should not depend on specific I/O devices or frameworks.
C) Use cross-platform libraries for all components.
D) Avoid using third-party APIs.


Question 3
Which principle helps achieve independent deployability of components?
A) Stable Dependencies Principle.
B) Interface Segregation Principle.
C) Single Responsibility Principle.
D) Common Closure Principle.


Question 4
Why is horizontal layering insufficient for true independence?
A) It enforces rigid dependencies between layers.
B) It doesn’t address vertical use-case boundaries.
C) It increases deployment complexity.
D) It violates the Open-Closed Principle.


Question 5
How does Clean Architecture handle database dependencies?
A) Business logic directly depends on SQL queries.
B) Database access is abstracted via interfaces.
C) Use a single global database connection.
D) Business logic and database are tightly coupled.


Question 6
Which is a valid strategy to delay decisions?
A) Hardcoding configuration values.
B) Using dependency injection for volatile components.
C) Relying on concrete framework APIs.
D) Embedding business rules in UI code.


Question 7
What is the risk of violating the Stable Dependencies Principle?
A) High-level policies depend on low-level details.
B) Components cannot be tested independently.
C) Changes propagate unpredictably across the system.
D) Code duplication increases.


Question 8
Which code snippet aligns with Clean Architecture principles?
Snippet 1:

class PaymentProcessor:def __init__(self, db_conn):self.db = db_conndef process(self, amount):self.db.execute("INSERT INTO payments ...")

Snippet 2:

class PaymentGateway(ABC):@abstractmethoddef process_payment(self, amount): passclass SqlPaymentGateway(PaymentGateway):def __init__(self, db_conn): ...def process_payment(self, amount): ...

A) Only Snippet 1.
B) Only Snippet 2.
C) Both.
D) Neither.


Question 9
What problem arises when business logic depends on UI frameworks?
A) UI changes force business logic rewrites.
B) Business logic becomes reusable across UIs.
C) It simplifies testing.
D) It improves deployment speed.


Question 10
Which is an example of vertical decoupling?
A) Separating code into MVC layers.
B) Isolating payment processing from user management.
C) Using interfaces for database access.
D) Implementing a plugin architecture.


Answers & Explanations

Answer 1
Correct: B, D
Explanation:

  • B) Delaying decisions prevents premature commitments (Ch15).
  • D) Managing dependencies is a core architectural goal (Ch15).
  • A) Performance is secondary to structural goals.
  • C) Coding standards are implementation details, not architectural goals.

Answer 2
Correct: B
Explanation:

  • B) Device independence means business logic isn’t tied to specific I/O (Ch15).
  • A) Code may require device-specific drivers but abstracts them.
  • C/D) Irrelevant to the core concept.

Answer 3
Correct: A
Explanation:

  • A) Stable Dependencies Principle ensures components depend only on stable abstractions (Ch16).
  • B/C/D) Address cohesion or interface design, not deployability.

Answer 4
Correct: B
Explanation:

  • B) Horizontal layers (e.g., UI, business logic) don’t isolate use cases vertically (Ch16).
  • A) Rigid dependencies are a symptom, not the root cause.

Answer 5
Correct: B
Explanation:

  • B) Abstracting database access via interfaces decouples business logic (Ch15).
  • A/C/D) Create tight coupling and violate independence.

Answer 6
Correct: B
Explanation:

  • B) Dependency injection defers concrete implementation choices (Ch16).
  • A/C/D) Fix decisions early, reducing flexibility.

Answer 7
Correct: A, C
Explanation:

  • A) High-level components depending on low-level details creates fragility.
  • C) Violations cause cascading changes (Ch16).
  • B/D) Unrelated to dependency stability.

Answer 8
Correct: B
Explanation:

  • Snippet 2 uses abstraction (PaymentGateway), aligning with DIP (Ch11/15).
  • Snippet 1 directly depends on a database, violating decoupling.

Answer 9
Correct: A
Explanation:

  • A) Tight coupling forces rewrites when UI changes (Ch16).
  • B/D) Independence improves reusability and deployment.

Answer 10
Correct: B
Explanation:

  • B) Vertical decoupling isolates use cases (e.g., payment vs. user management) (Ch16).
  • A/C) Horizontal layering or interface use.
  • D) Plugin architecture is a horizontal strategy.

Test Code Examples

Example for Q8 (Snippet 2):

from abc import ABC, abstractmethodclass PaymentGateway(ABC):@abstractmethoddef process_payment(self, amount): passclass SqlPaymentGateway(PaymentGateway):def __init__(self, db_conn):self.db = db_conndef process_payment(self, amount):self.db.execute("INSERT INTO payments ...")# Test
class MockDb:def execute(self, query): print(f"Mock: {query}")gateway = SqlPaymentGateway(MockDb())
gateway.process_payment(100)  # Output: "Mock: INSERT INTO payments ..."

Compilation: This Python code runs as-is, demonstrating dependency inversion.

Example for Q5:

class DatabaseInterface(ABC):@abstractmethoddef save_payment(self, amount): passclass PostgresAdapter(DatabaseInterface):def save_payment(self, amount): ...class BusinessLogic:def __init__(self, db: DatabaseInterface):self.db = dbdef process_payment(self, amount):self.db.save_payment(amount)

Test: BusinessLogic depends on an abstraction, enabling database swaps without code changes.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/899573.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【SPP】RFCOMM 层在SPP中互操作性要求深度解析

蓝牙串口协议&#xff08;SPP&#xff09;通过 RFCOMM 协议实现 RS232 串口仿真&#xff0c;其互操作性是设备互联的关键。本文基于蓝牙核心规范&#xff0c;深度解析 RFCOMM 层的能力矩阵、信号处理、流控机制及实战开发&#xff0c;结合状态机、流程图和代码示例&#xff0c;…

阻塞式IO与非阻塞IO的区别

阻塞式IO与非阻塞IO的区别 1. 阻塞式IO (Blocking I/O) 定义 当程序发起一个I/O操作&#xff08;如读取文件、网络数据&#xff09;时&#xff0c;进程会被挂起&#xff08;阻塞&#xff09;&#xff0c;直到操作完成或超时才会继续执行后续代码。在此期间&#xff0c;程序无法…

Gossip协议:分布式系统中的“八卦”传播艺术

目录 一、 什么是Gossip协议&#xff1f;二、 Gossip协议的应用 &#x1f4a1;三、 Gossip协议消息传播模式详解 &#x1f4da;四、 Gossip协议的优缺点五、 总结&#xff1a; &#x1f31f;我的其他文章也讲解的比较有趣&#x1f601;&#xff0c;如果喜欢博主的讲解方式&…

【C++初阶】----模板初阶

1.泛型函数 泛型编程&#xff1a;编写与类型无关的通用代码&#xff0c;是代码复用的一种手段。模板是泛型编程的基础。 2.函数模板 2.1函数模板的概念 函数模板代表了一个函数家族&#xff0c;该函数模板与类型无关&#xff0c;在使用时被参数化&#xff0c;根据实参类型…

git-- github的使用--账户和本地连接

以下指令在git 执行bash 流程&#xff1a;先看有没有密钥&#xff1b; 没有的话&#xff0c;在电脑生成密钥对&#xff0c;公钥复制到github&#xff1b; 要想使用https&#xff0c;配置令牌&#xff0c;注意令牌有期限问题&#xff0c;连接不了有可能是期限问题 一个电脑对…

OTN(Optical Transport Network)详解

OTN&#xff08;光传送网&#xff09;是一种基于**波分复用&#xff08;WDM&#xff09;**的大容量光传输技术&#xff0c;结合了SDH的运维管理优势和WDM的高带宽特性&#xff0c;广泛应用于骨干网、城域核心层及数据中心互联&#xff08;DCI&#xff09;。 1. OTN 的基本概念 …

Python 中列表(List)、元组(Tuple)、集合(Set)和字典(Dict)四大数据结构的完整对比

以下是 Python 中列表&#xff08;List&#xff09;、元组&#xff08;Tuple&#xff09;、集合&#xff08;Set&#xff09;和字典&#xff08;Dict&#xff09;四大数据结构的完整对比分析&#xff0c;结合了核心特性、操作方式和应用场景的深度总结&#xff1a; 一、核心特性…

Angular由一个bug说起之十五:自定义基于Overlay的Tooltip

背景 工具提示&#xff08;tooltip&#xff09;是一个常见的 UI 组件&#xff0c;用于在用户与页面元素交互时提供额外的信息。由于angular/material/tooltip的matTooltip只能显示纯文本&#xff0c;所以我们可以通过自定义Directive来实现一个灵活且功能丰富的tooltip Overlay…

软件工程面试题(十五)

1、servlet 创建过程以及ruquest,response,session的生命周期? Servlet的创建过程: 第一步 public class AAA extends HttpServlet{ 实现对应的doxxx方法 } 第二步: 在web.xml中配置 <servlet> <servlet-name></servlet-name> <servlet-c…

搭建QNX Software Center的Docker环境

背景 本人使用 Ubuntu Server 22.04 服务器&#xff0c;所以没有图形界面&#xff0c;而 QNX Software Center 需要图形界面。为了保证服务器环境的整理&#xff0c;计划使用Docker部署QNX Software Center 一瓶安装图形界面。本方既是实现方案的记录。 资源 Dockerfile&…

C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)

前言 C#/.NET/.NET Core技术前沿周刊&#xff0c;你的每周技术指南针&#xff01;记录、追踪C#/.NET/.NET Core领域、生态的每周最新、最实用、最有价值的技术文章、社区动态、优质项目和学习资源等。让你时刻站在技术前沿&#xff0c;助力技术成长与视野拓宽。 欢迎投稿、推荐…

粘包问题解决方案

粘包问题详解&#xff1a;TCP协议中的常见问题及Go语言解决方案 一、什么是粘包问题&#xff1f; 粘包问题是指在TCP通信中&#xff0c;发送方发送的多个独立消息在接收方被合并成一个消息接收的现象。换句话说&#xff0c;发送方发送的多条消息在接收方被“粘”在一起&#…

vue:突然发现onok无法使用

const that this;this.$confirm({title: "修改商品提示",content: "如果当前商品存在于商品活动库&#xff0c;则在商品活动库的状态会下架",onOk: function () {that.submitForm();}}); 突然发现 this.$confirm无法进入onok 最终发现是主题冲突&#x…

redis hashtable 的sizemask理解

在 Redis 的哈希表实现中&#xff0c;index hash & dict->ht[0].sizemask 是计算键值对应存储位置的核心操作。这个操作看起来简单&#xff0c;但背后涉及哈希表的内存布局和性能优化策略。我们通过以下步骤逐步解析其原理&#xff1a; 一、哈希表的设计目标 快速定位…

Ruby 命令行选项

Ruby 命令行选项 概述 Ruby 是一种广泛使用的编程语言,它拥有强大的命令行工具,可以帮助开发者进行各种任务。了解 Ruby 的命令行选项对于提高开发效率至关重要。本文将详细介绍 Ruby 的常用命令行选项,帮助开发者更好地利用 Ruby 的命令行功能。 Ruby 命令行选项概述 R…

【STM32】WDG看门狗(学习笔记)

学习来源----->江协科技STM32 WDG简介 WDG&#xff08;Watchdog&#xff09;看门狗看门狗可以监控程序的运行状态&#xff0c;当程序因为设计漏洞、硬件故障、电磁干扰等原因&#xff0c;出现卡死或跑飞现象时&#xff0c;看门狗能及时复位程序&#xff0c;避免程序陷入长…

Java 数据库连接池

HikariCP 老外开源的。 Spring Boot 2 之后默认选择的连接池。 号称性能最快的数据库连接池。 为什么性能好呢&#xff1f; ● 字节码级别的优化-尽量的利用 JIT 的内联手段 ● 字节码级别的优化-利用更容易被 JVM 优化的指令 ● 代码级别的优化-利用改造后的 FastList 代替…

Spring Boot中@Valid 与 @Validated 注解的详解

Spring Boot中Valid 与 Validated 注解的详解 引言Valid注解功能介绍使用场景代码样例 Validated注解功能介绍使用场景代码样例 Valid与Validated的区别结论 引言 在Spring Boot应用中&#xff0c;参数校验是确保数据完整性和一致性的重要手段。Valid和Validated注解是Spring …

C++搜索

功能扩展说明&#xff1a; 图类封装&#xff1a;将图数据结构封装为类&#xff0c;提高代码复用性 最短路径查找&#xff1a;基于BFS实现未加权图的最短路径查找 路径重构&#xff1a;通过parent数组回溯构建完整路径 异常处理&#xff1a;当路径不存在时返回空向量 复杂度分析…

2023第十四届蓝桥杯大赛软件赛国赛C/C++ 大学 B 组(真题题解)(C++/Java题解)

本来想刷省赛题呢&#xff0c;结果一不小心刷成国赛了 真是个小迷糊〒▽〒 但&#xff0c;又如何( •̀ ω •́ )✧ 记录刷题的过程、感悟、题解。 希望能帮到&#xff0c;那些与我一同前行的&#xff0c;来自远方的朋友&#x1f609; 大纲&#xff1a; 一、子2023-&#xff…