您可以引入參數對象:
class ParameterObject {
public final SomeClass!(TemplateParam) foo;
public final string[][string] someAA;
public final uint[] dataToProcess;
public final SomeEnumType flag;
private ParameterObject(
SomeClass!(TemplateParam) foo,
string[][string] someAA,
uint[] dataToProcess,
SomeEnumType flag) {
this.foo = foo;
this.someAA = someAA;
this.dataToProcess = dataToProcess;
this.flag = flag;
}
private static class Builder {
public SomeClass!(TemplateParam) foo;
public string[][string] someAA;
public uint[] dataToProcess;
public SomeEnumType flag;
public Builder foo(SomeClass!(TemplateParam) foo) {
this.foo = foo;
return this;
}
public Builder someAA(string[][string] someAA) {
this.someAA = someAA;
return this;
}
public Builder dataToProcess(uint[] dataToProcess) {
this.dataToProcess = dataToProcess;
return this;
}
public Builder flag(SomeEnumType flag) {
this.flag = flag;
return this;
}
public ParameterObject build() {
if (null == foo) throw Exception("init foo!");
if (null == someAA) throw Exception("init someAA!");
if (null == dataToProcess) throw Exception("init dataToProcess!");
if (null == flag) throw Exception("init flag!");
return new ParameterObject(foo, someAA, dataToProcess, flag);
}
}
}
現在,您的通話將查找例如:
SomeClass[string] myValue =
someFunction(
new ParameterObject.Build().
foo(myFoo).
someAA(myAA).
dataToProcess(myData).
flag(false).
build()
);
它在語言允許內嵌的創作更容易處理類似案件地圖:
someFunction(
Map.new(
foo => myFoo,
someAA => myAA,
dataToProcess => myData,
flag => false
)
限定符final
意味着一個字段只能從類的構造函數中設置。在類之前的限定符static
意味着該類不與其外部類相關聯,即不能訪問/變更其字段。
我同意。對於非常長的參數列表,每行一個參數也有它自己的問題....但是我從來沒有看到任何其他解決方案只要您需要長參數列表就可以更好地工作。當我這樣做時,我也傾向於對齊類型和參數名稱......可能會使它稍微更具可讀性。 – SuperMagic 2010-01-28 17:52:04
此外,如果您的參數列表比這長得多,那麼這是一個很好的跡象表明某些重構是有序的。 – Aaron 2015-03-13 14:26:44