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

Maintainability issue of refactoring "fA()" and "fB()" to "fAB(){return report;}"

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

随着年龄的增长,我发现将一些类似的函数捆绑在一起更方便,将旧函数的return结果分组为一个"Report"。

"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?

创建 non-member 可以 return 更高级别对象而不是更改现有 类.

的函数

例如,不写[=12=的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?

使用 non-member 函数来扩展功能而不是修改现有的 类。

根据 Scott Meyers 的说法,using non-member functions improves encapsulation.

使用non-member函数添加新功能也遵循The Open/Closed Principle