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.pswp.cn/news/899573.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/899573.shtml
英文地址,請注明出處:http://en.pswp.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…