Java方法命名约定;委托参数名称?

时间:2014-08-20 04:09:53

标签: java

在尝试编写简洁的方法名称时,通常会将一些信息委托给参数名吗?也就是说,而不是:

public Foos getFoosForBar(int barId);

我们可以简单地使用:

public Foos getFoos(int barId);

我确实认识到第二个版本可能会遇到使用idential类型的不同params重载的问题,例如:

public Foos getFoos(int barId);
...
public Foos getFoos(int lobsterId);

但与此同时,如果方法名称过于明确,则可能会变得荒谬,例如:

public Foos getFoosForBarWithLobsterAndSteak(int barId, int lobsterId, int steakId);

我知道这里没有任何银弹,所以我想我只是在征求意见。

1 个答案:

答案 0 :(得分:3)

使用int作为参数不会给出任何重载空间,但使用参数类型会:

public Foos getFoos(Bar bar) { /* use bar.id */ }
public Foos getFoos(Lobster lobster) { /* use lobster.id */ }
public Foos getFoos(TheWorks theWorks) { /* as complex as you like */ }

将许多参数捆绑到一个对象中是参数对象模式。

还有使用的构建器模式可能如下所示:

Foo foo = FooBuilder.create()
    .with(bar)
    .with(lobster)
    .with(steak)
    .get();

其中get()方法使用先前调用中收集的所有信息来决定要获取的内容。这种流畅的编程风格易于使用和阅读。

with()方法进行编码,如下所示:

public FooGetter with(Bar bar) {
    this.bar = bar;
    return this;
}

get()是这样的:

public Foo get() {
    // decide on your foo given all the fields set (or not) via with() methods
    return someFoo;
}
相关问题