69 lines
2.4 KiB
Markdown
69 lines
2.4 KiB
Markdown
---
|
||
title: "DRY Principle"
|
||
type: concept
|
||
tags:
|
||
- software-engineering
|
||
- iac
|
||
- best-practices
|
||
sources: [ctp-topic-48-terraform-vs-terragrunt]
|
||
last_updated: 2026-04-26
|
||
---
|
||
|
||
# DRY Principle
|
||
|
||
## Definition
|
||
|
||
DRY(Don't Repeat Yourself,勿重复自己)是一项软件工程原则,主张:**系统中的每一条知识必须有一个单一的、明确的、权威的表示**。DRY 的核心目标是减少重复代码和配置,提高系统的可维护性、可扩展性和可测试性。
|
||
|
||
## Core Idea
|
||
|
||
> "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system."
|
||
|
||
DRY 不是简单的"不复制粘贴",而是更深层的原则:**避免重复的知识**。这包括:
|
||
- 代码逻辑
|
||
- 配置文件
|
||
- 文档注释
|
||
- 数据结构
|
||
|
||
## DRY in IaC
|
||
|
||
在基础设施即代码(IaC)领域,DRY 尤为重要,因为基础设施配置往往需要在多个环境(dev/staging/prod)中复用:
|
||
|
||
| 实践 | 说明 |
|
||
|------|------|
|
||
| **Terragrunt** | 封装 Terraform,通过 `remote_state` 和 `include` 块统一管理跨环境的 provider 和状态配置 |
|
||
| **Terraform Modules** | 将可复用的基础设施组件抽象为模块,避免在每个环境中重复定义 |
|
||
| **Service Catalog** | 企业级模块目录,支持三级复用(单账户→产品团队→跨团队) |
|
||
| **Hierarchical Configuration** | 层级配置继承,父级定义通用配置,子级覆盖特定值 |
|
||
|
||
**来源**: [[ctp-topic-48-terraform-vs-terragrunt]], [[ctp-topic-3-deploy-and-maintain-infrastructure]]
|
||
|
||
## DRY vs WET
|
||
|
||
| 原则 | 全称 | 结果 |
|
||
|------|------|------|
|
||
| **DRY** | Don't Repeat Yourself | 一次定义,多次引用 |
|
||
| **WET** | Write Everything Twice | 多次重复,维护成本高 |
|
||
|
||
WET 的典型反模式:
|
||
- 复制粘贴配置到每个环境
|
||
- 硬编码值而非使用变量
|
||
- 注释与代码不同步
|
||
|
||
## When NOT to Apply DRY
|
||
|
||
DRY 不是绝对的,在以下情况下适度重复是可接受的:
|
||
- **性能优化**:内联代码可能比函数调用更快
|
||
- **可读性**:过度抽象可能导致代码难以理解
|
||
- **解耦**:强制的 DRY 可能增加组件间的耦合
|
||
|
||
## Related Concepts
|
||
|
||
- [[Infrastructure-as-Code]] — DRY 原则的重要应用领域
|
||
- [[Terraform]] — Terragrunt 的底层引擎
|
||
- [[Terragrunt]] — DRY 原则在 Terraform 生态中的具体实现
|
||
|
||
## Related Sources
|
||
|
||
- [[ctp-topic-48-terraform-vs-terragrunt]]
|