将一个参数添加到在我的项目中被100个不同位置调用的方法 - 应该采取什么适当的方法?

3

我正在处理一个代码库,其中有一个实用类负责为用户生成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)将从许多不同的地方调用。例如100+。

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

我修改了方法签名以接收附加参数,但我发现自己不得不编写一个正则表达式来查找/替换所有的方法调用。它可以工作,但感觉这种方式不对。

我应该怎么做?


使用自动重构工具怎么样?更改方法签名... - gontard
@Paul,你认为你的问题得到了回答吗?如果是这样,请考虑接受其中一个答案,或者详细说明问题,以便改进答案。 - aioobe
5个回答

6
你可以创建一个新的重载方法,接受第四个参数,并让旧方法调用新方法时使用 null 作为第四个参数。 之前:
public void putDataInRowColumn(int row, int column, int data) {
    // implementation
}

之后:

// 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
}

相关:


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);
}

您也可以使用现代IDE通过“添加参数”重构该方法,并为新参数提供合理的默认值,例如您的情况下是null。 :)
另外,我认为您应该避免将null作为“无样式”值,因为当您看到像putDataInRowColumn(0, 5, data, null)这样的代码时,它几乎没有什么意义——不是putDataInRowColumn(0, 5, data, Styling.NONE)更容易阅读吗?

3
仅供参考,重构将在“更改签名”下进行。 - Marko Topolnik

2

你需要重载这个方法。

新的方法标记为:

putDataInRowColumn(SomeType row, SomeType column, SomeType data, SomeType style)

在这个方法中,您将检查风格参数。

然后putDataInRowColumn(row, column, data) 的实现如下:

putDataInRowColumn(row, column, data) { putDataInRowColumn(row, column, data, null); }

如果您遵循这个步骤,则不必对之前的代码进行重构。


2

在同一个类中编写另一个重载方法putDataInRowColumn(row, column, data, additional),99%的类调用putDataInRowColumn(row, column, data),而改变1%的类来调用这个新方法。

//edit old method to call newer one.
putDataInRowColumn(row, column, data) 
{
putDataInRowColumn(row, column, data, null)
}

1
如果99%的调用不需要第4个参数,最好使用方法重载,这样99%的调用保持不变。 例如(我对参数类型和返回类型进行了一些任意假设):
现有的方法:
putDataInRowColumn(int row, int column, SomeType data) {
    putDataInRowColumn(row, column, data, null);
}

新方法:

putDataInRowColumn(int row, int column, SomeType data, SomeOtherType) {
    the actual logic
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接