Administrator
发布于 2025-12-05 / 0 阅读
0
0

决策-执行分离:先写决策还是先写执行?

前言

在 决策 - 执行模式中,我们在写代码,或者说设计代码时,是会先写执行部分的代码,还是写决策部分的代码。前者的理由是,我们在写执行代码的时候,才会具体知道需要哪些决策,确定了决策需要返回的结果类型,再写决策部分;后者则可能有不同考虑。

早期认知:先写执行部分(主流实践)

大多数开发者自然地先写执行部分,原因如下:

为什么先写执行部分更自然?

// 1. 从具体需求出发
// 用户需求:"我需要能上传文件"
// → 自然先写 uploadFile() 函数

async function uploadFile(file: File) {
    // 先关心具体怎么做
    const size = file.size;
    const type = file.type;
    // 哦,需要检查文件大小
    if (size > MAX_SIZE) {
        throw new Error('文件太大');
    }
    // 还需要检查文件类型
    if (!ALLOWED_TYPES.includes(type)) {
        throw new Error('不支持的文件类型');
    }
    // 然后执行上传...
}

优点:

  • 符合认知顺序:从 " 做什么 " 到 " 为什么这么做 "
  • 避免过度设计:先解决实际问题
  • 快速原型:更快得到可运行代码

中期认知:先写决策部分(设计驱动)

随着经验增长,很多开发者转向先写决策部分:

为什么先写决策部分更专业?

// 2. 从业务规则出发
// 思考:"上传文件有哪些约束条件?"

// 先定义决策规则(纯函数)
class FileUploadPolicy {
    static canUpload(file: File): DecisionResult {
        return {
            allowed: file.size <= MAX_SIZE && 
                     ALLOWED_TYPES.includes(file.type),
            reason: file.size > MAX_SIZE ? '文件太大' :
                   !ALLOWED_TYPES.includes(file.type) ? '类型不支持' : null
        };
    }

    static computeStoragePath(file: File, user: User): string {
        // 纯计算,无副作用
        return `/users/${user.id}/uploads/${Date.now()}_${file.name}`;
    }
}

// 然后写执行部分(很简单)
async function uploadFile(file: File, user: User) {
    const decision = FileUploadPolicy.canUpload(file);
    if (!decision.allowed) {
        throw new Error(decision.reason);
    }

    const path = FileUploadPolicy.computeStoragePath(file, user);
    await storageService.save(file, path);
}

优点:

  • 关注点分离:一次只关注一件事
  • 可测试性:决策逻辑容易单元测试
  • 业务明确:业务规则显式化

现代最佳实践:三明治法(测试先行)

现在主流的 TDD/BDD 实践是:

1. 先写测试(定义期望行为)

// 测试先行,定义"什么情况下应该发生什么"
describe('文件上传', () => {
    it('应该拒绝超过10MB的文件', () => {
        const largeFile = createFile({ size: 11 * 1024 * 1024 });
        const result = UploadService.canUpload(largeFile);
        expect(result.allowed).toBe(false);
        expect(result.reason).toBe('文件太大');
    });

    it('应该允许合法文件并返回存储路径', async () => {
        const file = createFile({ size: 5 * 1024 * 1024, type: 'image/png' });
        const user = createUser({ id: '123' });
        const result = await UploadService.upload(file, user);
        expect(result.path).toMatch(/^\/users\/123\/uploads\/\d+_file\.png$/);
    });
});

2. 实现决策逻辑(通过测试)

// 实现决策部分以满足测试
class UploadDecisionMaker {
    static makeDecision(file: File): UploadDecision {
        // 纯业务逻辑
        if (file.size > this.getMaxSize()) return { allowed: false, reason: '文件太大' };
        if (!this.isAllowedType(file.type)) return { allowed: false, reason: '类型不支持' };

        return { allowed: true };
    }

    private static getMaxSize(): number { /* ... */ }
    private static isAllowedType(type: string): boolean { /* ... */ }
}

3. 实现执行逻辑(通过测试)

// 实现执行部分
class UploadExecutor {
    async execute(file: File, user: User, decision: UploadDecision): Promise<UploadResult> {
        if (!decision.allowed) {
            throw new UploadError(decision.reason);
        }

        const path = PathGenerator.generate(file, user);
        await StorageService.save(file, path);

        return { success: true, path };
    }
}

实战建议:根据情况选择

适合先写执行部分的情况

  1. 探索性项目 - 不确定最终形态
  2. 快速原型 - 需要尽快看到效果
  3. 简单功能 - 决策逻辑很直接
  4. 个人项目 - 不需要长期维护

适合先写决策部分的情况

  1. 复杂业务规则 - 有明确的业务约束
  2. 团队协作 - 需要明确接口契约
  3. 长期维护项目 - 重视可测试性
  4. 核心领域逻辑 - 需要清晰表达业务

我的建议:双循环开发法

结合两者优点,我推荐这个方法:

// 第一轮:快速实现(先执行)
async function processOrder(order: Order) {
    // 1. 快速写出完整逻辑
    if (order.items.length === 0) {
        throw new Error('订单为空');
    }

    if (order.customer.balance < order.total) {
        throw new Error('余额不足');
    }

    // ... 更多业务规则和执行代码混在一起

    await saveOrder(order);
    await sendConfirmation(order.customer.email);
}

// 第二轮:重构分离(提取决策)
class OrderProcessor {
    // 2. 提取决策逻辑
    private validateOrder(order: Order): ValidationResult {
        const errors: string[] = [];

        if (order.items.length === 0) {
            errors.push('订单为空');
        }

        if (order.customer.balance < order.total) {
            errors.push('余额不足');
        }

        return { isValid: errors.length === 0, errors };
    }

    // 3. 精简执行逻辑
    async process(order: Order): Promise<void> {
        const validation = this.validateOrder(order);
        if (!validation.isValid) {
            throw new Error(validation.errors.join(', '));
        }

        await this.executeOrder(order);
    }

    private async executeOrder(order: Order): Promise<void> {
        await saveOrder(order);
        await sendConfirmation(order.customer.email);
    }
}

参考书籍中的观点

《整洁架构》(Robert C. Martin)

" 先编写业务规则(用例),它们是系统的核心。然后再编写适配器、框架和 UI。"

《领域驱动设计》(Eric Evans)

" 首先理解并建模核心领域概念,这些概念通常表现为决策规则。"

《重构》(Martin Fowler)

" 先让代码工作,然后让它变好。通常会先写混合逻辑,再通过重构分离关注点。"

总结表格

方法 适用场景 优点 缺点
先执行 探索性开发、原型 快速反馈、符合直觉 容易产生 " 上帝函数 "
先决策 复杂业务、团队协作 设计清晰、易于测试 可能过度设计
测试先行 质量要求高的项目 行为明确、回归安全 学习成本高
双循环法 大多数项目 平衡速度和质量 需要纪律性

最终建议:

  • 如果你是初学者或做原型,先写执行部分
  • 如果你是中级开发者,尝试先写决策部分
  • 如果你是高级开发者或团队合作,采用测试先行
  • 大多数情况下,双循环法是最实用的

最重要的是意识到两者的区别——这是做出好设计的前提。


评论