当我的程序还很年轻的时候,通常有很多做简单事情的函数。
随着年龄的增长,我发现将一些相似的函数捆绑在一起,将旧函数的返回结果归为一个“Report”会更方便。
“报告”可以作为不同模块之间的通信包轻松传递。
例子1
代码V1
class B{
float getWidth(C c){
float width= ... (very cheap function about "c") ;
return width;
}
float getHeight(C c){
float height= ... (very cheap function about "c") ;
return height;
}
};
代码 V2
class ReportSize { float width; float height; }
class B{
ReportSize getSize(C c){ //<-- grouped
float width = ... ;
float height= ... ;
return ReportSize(width ,height);
}
};
例子2
代码V1
class D{
Vector3 calculateNarrow(){ ... }
Vector3 calculateBoard(){ ... }
};
代码 V2
class ReportVector3Pair{
Vector3 resultNarrow;
Vector3 resultBoard;
Vector3 get(NARROW_OR_BOARD paramEnum){
//return "resultNarrow" or "resultBoard"
}
};
class D{
ReportVector3Pair calculate(){ ... } //<-- grouped
};
问题
重构花费了一些开发时间。必须手动重构代码的所有位置(最多 100 个调用方)以匹配新签名。
如何最大限度地减少以后需要重构它的机会?如果将来可能发生,如何最小化重构的成本?
最佳答案
How to minimize the chance of the need to refactor it later?
创建可以返回更高级别对象而不是更改现有类的非成员函数。
例如,不写B
的V2,保留现有的B
并使用:
class ReportSize { float width; float height; }
ReportSize getReportSize(B const& b, C c)
{
return {b.getWidth(c), b.getHeight(c)}
}
同样,不要创建 D
的 V2,而是保留现有的 D
并使用:
Vector3 calculate(D const& d, NARROW_OR_BOARD paramEnum) {
//return "resultNarrow" or "resultBoard"
}
How to minimize cost of the refactoring if it may happen in future?
使用非成员函数来扩展功能而不是修改现有类。
根据 Scott Meyers 的说法,using non-member functions improves encapsulation.
使用非成员函数添加新功能也遵循The Open/Closed Principle .
关于c++ - 重构 "fA()"和 "fB()"为 "fAB(){return report;}"的可维护性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41974643/