![](https://csdnimg.cn/release/download_crawler_static/86313175/bg4.jpg)
不过,如果函数是 private 私有函数,影响范围有限,或者拆分之后的两个函数经常同时被
调用,我们可以酌情考虑保留标识参数。示例代码如下所示:
除了布尔类型作为标识参数来控制逻辑的情况外,还有一种“根据参数是否为 null”来控
制逻辑的情况。针对这种情况,我们也应该将其拆分成多个函数。拆分之后的函数职责更明
确,不容易用错。具体代码示例如下所示:
复制代码
1
2
3
4
5
public void buyCourse(long userId, long courseId, boolean isVip);
// 将其拆分成两个函数
public void buyCourse(long userId, long courseId);
public void buyCourseForVip(long userId, long courseId);
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
// 拆分成两个函数的调用方式
boolean isVip = false;
//...省略其他逻辑...
if (isVip) {
buyCourseForVip(userId, courseId);
} else {
buyCourse(userId, courseId);
}
// 保留标识参数的调用方式更加简洁
boolean isVip = false;
//...省略其他逻辑...
buyCourse(userId, courseId, isVip);
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public List<Transaction> selectTransactions(Long userId, Date startDate, Date e
if (startDate != null && endDate != null) {
// 查询两个时间区间的transactions
}
if (startDate != null && endDate == null) {
// 查询startDate之后的所有transactions
}
if (startDate == null && endDate != null) {
// 查询endDate之前的所有transactions
}
if (startDate == null && endDate == null) {
// 查询所有的transactions
}
}