刚开始的代码
1 class 将概念显式化1
2 {
3 public void 请假(Guid employeeId, DateTime startDate, DateTime endDate)
4 {
5 var 剩余天数 = 获取员工可以请假的剩余天数(employeeId);
6 var 请假天数 = (endDate - startDate).Days;
7
8 if (请假天数 > 剩余天数)
9 {
10 //抛出请假异常
11 }
12
13 //处理正常的请假逻辑
14 }
15
16 private int 获取员工可以请假的剩余天数(Guid employeeId)
17 {
18 return 10;
19 }
20 }
进一步重构
1 class 将概念显式化2
2 {
3 public void 请假(Guid employeeId, DateTime startDate, DateTime endDate)
4 {
5 if (!员工是否满足请假条件(employeeId, startDate, endDate))
6 {
7 //抛出请假异常
8 }
9
10 //处理正常的请假逻辑
11 }
12
13 private bool 员工是否满足请假条件(Guid employeeId, DateTime startDate, DateTime endDate)
14 {
15 var 剩余天数 = 获取员工可以请假的剩余天数(employeeId);
16 var 请假天数 = (endDate - startDate).Days;
17
18 return 请假天数 <= 剩余天数;
19 }
20
21 private int 获取员工可以请假的剩余天数(Guid employeeId)
22 {
23 return 10;
24 }
25 }
继续重构
1 class 将概念显式化3
2 {
3 public void 请假(员工请假规约 规约)
4 {
5 if (!规约.是否满足())
6 {
7 //抛出请假异常
8 }
9
10 //处理正常的请假逻辑
11 }
12 }
13
14 class 员工请假规约
15 {
16 private Guid employeeId;
17 private DateTime startDate;
18 private DateTime endDate;
19
20 public 员工请假规约(Guid employeeId, DateTime startDate, DateTime endDate)
21 {
22 this.employeeId = employeeId;
23 this.startDate = startDate;
24 this.endDate = endDate;
25 }
26
27 public bool 是否满足()
28 {
29 var 剩余天数 = 获取员工可以请假的剩余天数(employeeId);
30 var 请假天数 = (endDate - startDate).Days;
31
32 return 请假天数 <= 剩余天数;
33 }
34
35 private int 获取员工可以请假的剩余天数(Guid employeeId)
36 {
37 return 10;
38 }
39 }