gpt4 book ai didi

oop - 了解简洁代码示例中的单一责任主体 SRP

转载 作者:行者123 更新时间:2023-12-01 23:51:16 26 4
gpt4 key购买 nike

目前我正在阅读 Uncle Bob 的干净代码书,在查看以下示例时在函数部分:-

public Money calculatePay(Employee e)
throws InvalidEmployeeType {
switch (e.type) {
case COMMISSIONED:
return calculateCommissionedPay(e);
case HOURLY:
return calculateHourlyPay(e);
case SALARIED:
return calculateSalariedPay(e);
default:
throw new InvalidEmployeeType(e.type);
}
}

鲍勃叔叔说:-

There are several problems with this function. First, it’s large, and when new employee types are added, it will grow. Second, it very clearly does more than one thing. Third, it violates the Single Responsibility Principle7 (SRP) because there is more than one reason for it to change. Fourth, it violates the Open Closed Principle8 (OCP) because it must change whenever new types are added

他提出如下解决方案:-

public abstract class Employee {
public abstract boolean isPayday();
public abstract Money calculatePay();
public abstract void deliverPay(Money pay);
}
-- -- -- -- -- -- -- -- -
public interface EmployeeFactory {
public Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType;
}
-- -- -- -- -- -- -- -- -
public class EmployeeFactoryImpl implements EmployeeFactory {
public Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType {
switch (r.type) {
case COMMISSIONED:
return new CommissionedEmployee(r);
case HOURLY:
return new HourlyEmployee(r);
case SALARIED:
return new SalariedEmploye(r);
default:
throw new InvalidEmployeeType(r.type);
}
}
}

我不能完全理解这个例子的想法,我脑子里有一些问题我找不到答案:-

1- 在添加新员工时的第一个代码中,它会增长。是的,但在解决方案中也会出现这种情况,所以有什么区别?

2-第一个例子如何做不止一件事。它只计算付款“在同一抽象级别的功能”请注意,如果我们认为抛出错误是另一回事,解决方案也会这样做

最佳答案

First, it’s large, and when new employee types are added, it will grow.

你是对的,该解决方案并没有真正缩短整体代码大小,而且当添加新的员工类型时,它仍然会整体增长。

Second, it very clearly does more than one thing.

原始版本既处理调度到正确的付款计算函数,又计算付款。提议的解决方案解决了这个问题。 HourlyEmployee.calculatePay() 现在只计算 HourlyEmployee 等的工资。EmployeeFactoryImpl 根据 Employee 处理 dispatch > 它返回的实现。

Third, it violates the Single Responsibility Principle (SRP) because there is more than one reason for it to change.

如果薪酬计算逻辑需要改变,原来的calculatePay也需要改变。如果添加了新的员工类型,它也需要更改。添加新员工类型时,该解决方案不需要更改 calculatePay。因此,只有一个责任和一个改变的理由。

Fourth, it violates the Open Closed Principle (OCP) because it must change whenever new types are added

回到1,当添加新的员工类型时,整体代码长度仍然会发生变化。但是,只有与处理员工类型相关的部分需要更改。专门用于计算薪酬的代码根本不需要更改。这样需要扩展的部分是开放的,与扩展无关的部分是封闭的。

关于oop - 了解简洁代码示例中的单一责任主体 SRP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26361032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com