c++ - 重构 "fA()"和 "fB()"为 "fAB(){return report;}"的可维护性问题

标签 c++ architecture maintainability

当我的程序还很年轻的时候,通常有很多做简单事情的函数。

随着年龄的增长,我发现将一些相似的函数捆绑在一起,将旧函数的返回结果归为一个“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/

相关文章:

c++ - 编译器可以忽略 constexpr 函数中 "not-taken"分支的评估吗?

architecture - 拥有仅包含静态方法的模型有意义吗?

performance - 速度比较-解释语言中的程序与OO

regex - 你如何理解一行写的正则表达式?

c# - Visual Studio 中的代码指标计算

c++ - 我可以使用类级别的 typedef 作为基类的模板参数吗?

c++ - 从指向基类型的指针 vector ,返回派生类型的第一个元素,转换为派生类型

c++ - 仅当变量在 C++ 中可转换时,如何将变量从 int 转换为模板参数

Mysql日志表架构

objective-c - 调用继承的私有(private)方法的完美解决方案