我经常发现自己有这样的方法签名:
public returnType doStuff(mandatoryParam, calculableParam1, calculableParam2);
在这些情况下,我有时想支持这些不同的方法签名:
public returnType doStuff(mandatoryParam);
public returnType doStuff(mandatory, calculable1);
public returnType doStuff(mandatory, calculable2);
public returnType doStuff(mandator, calculable1, calculable2);
像这样进行重载时,最好让重载将 null 传递给基方法,如下所示:
public returnType doStuff(mandatoryParam){
doStuff(mandotryParam, null, null)
}
public returnType doSTuff(mandatoryParam, calculable1, calculable2){
if(null == calculable1){
calculable1 = calculate();
}
.
.
.
}
或者最好计算可计算的参数,然后将它们传递给基本方法,如下所示:
public returnType doStuff(mandatoryParam){
Calculable calc1 = figureItOut1();
Calculable calc2 = figureItOut2();
doStuff(mandotryParam, calc1, calc2);
}