将参数添加到从我的项目中的100个不同位置调用的方法 - 什么是正确的方法?

Pau*_*aul 3 java design-patterns

所以我正在开发一个代码库,并且有一个实用程序类可以处理为用户生成excel文档.

它有一个叫做的方法 putDataInRowColumn(row, column, data)

它有很多像putObjectsIntoExcel(myBigClass blah)和的方法 putObjectsIntoSpecialExcelType(myBigClass blah)

它调用了像putObjectIntoSpecialRowType(blah.foo(), rowIndex, specialConditions)和的方法putObjectIntoTotallydifferentRowType(blah.bar(), rowIndex, specialConditions)

所有这一切的要点是该方法putDataInRowColumn(row, column, data)从一堆不同的地方被称为公制buttload.像100+.

现在,考虑到这个遗留代码,我需要修改方法以获取其他参数 - 样式信息.99%的方法现在将'null'作为第四个参数,1%将接收包含样式信息的对象.

我修改了方法签名,以接收附加参数,但我发现自己必须编写一个正则表达式来查找/替换所有方法调用.它有效,但这感觉就像走错了路.

我应该怎么做?

aio*_*obe 6

您创建一个新的重载方法,该方法接受第四个参数,并让旧方法使用null第四个参数调用新方法.

之前:

public void putDataInRowColumn(int row, int column, int data) {
    // implementation
}
Run Code Online (Sandbox Code Playgroud)

后:

// 99% calls this
public void putDataInRowColumn(int row, int column, int data) {
    // Delegates to new method with null as "default" argument
    putDataInRowColumn(row, column, data, null);
}

// Called by new code
public void putDataInRowColumn(int row, int column, int data, Style style) {
    // implementation
}
Run Code Online (Sandbox Code Playgroud)

有关:


gus*_*afc 5

让旧的继续putDataInRowColumn(row, column, data)存在,并让它将其调用委托给putDataInRowColumn(row, column, data, null)

public static Something putDataInRowColumn(int row, int column, Whatever data){
    return putDataInRowColumn(row, column, data, null);
}
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您还可以使用现代 IDE 使用“添加参数”重构方法,并为新参数提供合理的默认值null。:)

在这一点上,我还认为您应该避免null使用“无样式”值,因为当您看到类似这样的代码时,它毫无意义putDataInRowColumn(0, 5, data, null)- 不是putDataInRowColumn(0, 5, data, Styling.NONE)更容易阅读吗?

  • 只是为了定位,重构将在“更改签名”下。 (3认同)