语言无关 – 使用一个常量作为参数的方法与几种方法

在Kent Beck的
Implementation Patterns中,人们可以阅读

“A common use of constants is to
communicate variations of a message in
an interface. For example, to center
text you could invoke
setJustification(Justification.CENTERED).
One advantage of this style of API is
that you can add new variants of
existing methods by adding new
constants without breaking
implementors. However, these messages
don’t communicate as well as having a
separate method for each variation. In
this style, the message above would be
justifyCentered(). An interface where
all invocations of a method have
literal constants as arguments can be
improved by giving it separate methods
for each constant value.”

为什么是这样?通常,当我编码时,我注意到我有几个类似的无参数方法,可以简化为一个,带有参数,如下例所示,

void justifyRight()
void justifyLeft()
void justifyCentered()

我通常会做出与Kent建议相反的方法,即将其分组

setJustification(Justification justification)

你通常如何处理这种情况?这是完全主观的,还是有一个非常强烈的理由让我看不出肯特对此事的看法?

谢谢

最佳答案 文件访问方法通常具有关于读/写模式的参数,是否创建不存在的文件,安全属性,锁定模式等.想象一下,如果为每个有效的参数组合创建单独的方法,您将拥有多少方法!

我强调了支持单独方法的最大理由;它是故障安全的,因为您可以严格控制API.如果不公开此类参数,则调用者无法传入无效参数或参数的无效组合.这也意味着参数验证不太复杂.

但是,我并不赞成这种做法. API应该是精心设计的,应该是change as little as possible. Kent Beck打破API变化:

One advantage of [parameterized methods] is that you can add new variants of existing methods by adding new constants without breaking implementors.

他支持单独方法的论点是:

However, [parameterized methods] don’t communicate as well as having a separate method for each variation.

我不同意.方法参数可以是可读的.特别是与命名参数组合,这是一种由多种语言支持的功能.此外,单独的方法会导致混乱的API.

点赞