CleanCode:一个方法一个功能

在coding过程中,一个方法一个功能是我一直坚持的原则。这样的代码风格可以让逻辑更加清晰,原本几行没有含义的代码被赋予了一个函数名后变得更有意义。

有一次在公司代码里看到了一个方法,真的要吐了,一个方法800行!!!(程序员的自我修养 和 代码管理呢?????)


一个方法一个功能的实践:

Details
A useful guide as to whether a function is doing only one thing is given in “Clean Code” by Robert C Martin.

“another way to know that a function is doing more than “one thing” is if you can extract another function from it with a name that is not merely a restatement of its implementation.”

Bad

1
2
3
4
5
6
7
8
9
10
public void updateFooStatusAndRepository(Foo foo) {
if ( foo.hasFjord() ) {
this.repository(foo.getIdentifier(), this.collaborator.calculate(foo));
}

if (importantBusinessLogic()) {
foo.setStatus(FNAGLED);
this.collaborator.collectFnagledState(foo);
}
}

Better

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public void registerFoo(Foo foo) {
handleFjords(foo);
updateFnagledState(foo);
}

private void handleFjords(Foo foo) {
if ( foo.hasFjord() ) {
this.repository(foo.getIdentifier(), this.collaborator.calculate(foo));
}
}

private void updateFnagledState(Foo foo) {
if (importantBusinessLogic()) {
foo.setStatus(FNAGLED);
this.collaborator.collectFnagledState(foo);
}
}

You’ve gone too far

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public void registerFoo(Foo foo) {
handleFjords(foo);
updateFnagledState(foo);
}

private void handleFjords(Foo foo) {
if ( foo.hasFjord() ) {
this.repository(foo.getIdentifier(), this.collaborator.calculate(foo));
}
}

private void updateFnagledState(Foo foo) {
if (importantBusinessLogic()) {
updateFooStatus(foo);
this.collaborator.collectFnagledState(foo);
}
}

private void updateFooStatus(Foo foo) {
foo.setStatus(FNAGLED);
}