长参数列表

消除长参数列表

  • 我们应该编写“短小”的代码

  • 参数列表越少,越好

  • **一个方法的第一选择是没有参数,第二个选择是只有一个参数,稍次是两个参数。三个以上的参数简直无法忍受。 **– 代码整洁之道

将参数列表封装成对象

案例1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

public void createBook(final String title,
final String introduction,
final URL coverUrl,
final BookType type,
final BookChannel channel,
final String protagonists,
final String tags,
final boolean completed) {
...
Book book = Book.builder
.title(title)
.introduction(introduction)
.coverUrl(coverUrl)
.type(type)
.channel(channel)
.protagonists(protagonists)
.tags(tags)
.completed(completed)
.build();

this.repository.save(book);
}

修正:

  • 增加一个封装类
1
2
3
4
5
6
7
8
9
10
11
12

public class NewBookParamters {
private String title;
private String introduction;
private URL coverUrl;
private BookType type;
private BookChannel channel;
private String protagonists;
private String tags;
private boolean completed;
...
}
1
2
3
4

public void createBook(final NewBookParamters parameters) {
...
}

移除标记参数

1
2
3
4
5
6
7

public void editChapter(final long chapterId,
final String title,
final String content,
final boolean apporved) {
...
}

问题:前几个参数都是章节的必要信息,后面apporved是标记是否审核通过,这个参数其实是一个标记,标记后面的流程可能不同。

修正:这里我们可以将参数列表代表的不同路径拆分出来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

// 普通的编辑,需要审核
public void editChapter(final long chapterId,
final String title,
final String content) {
...
}


// 直接审核通过的编辑
public void editChapterWithApproval(final long chapterId,
final String title,
final String content) {
...
}

长参数列表
http://example.com/长参数列表/
作者
Panyurou
发布于
2022年3月31日
许可协议