具有许多参数的函数——将它们作为结构体

Functions with many parameters - making them as structs

本文关键字:结构体 许多 参数 函数      更新时间:2023-10-16

我正在为内部需求编写API,因此易用性是最优先考虑的问题之一。我想知道我是否像下面的例子那样做得太过火了。

求解逆大地测量问题的函数取两点的地理坐标,计算两点之间的距离和两点之间的近似角(角度)。

易用性优化的传统解决方案可能看起来像这样(请不要介意名称的长度,我知道还有改进的空间):

class Angle;
class GeoCoordinate;
...
struct InverseGeodeticOut
{
    Angle forwardAzimuth;
    Angle backAzimuth;
    double distance;
};
InverseGeodeticOut inverseGeodetic(const GeoCoordinate &firstPoint,
                                   const GeoCoordinate &secondPoint);
// or
void inverseGeodetic(const GeoCoordinate &firstPoint,
                     const GeoCoordinate &secondPoint,
                     InverseGeodeticOut *result);

我的问题是,如果再进一步为用户节省一些输入,这是否合理:

class Angle;
class GeoCoordinate;
...
struct InverseGeodetic
{
    InverseGeodetic();
    InverseGeodetic(const GeoCoordinate &firstPoint,
                    const GeoCoordinate &secondPoint);
    Angle forwardAzimuth;
    Angle backAzimuth;
    double distance;
};
// so the usages would be
InverseGeodeticOut inverse = inverseGeodetic(firstPoint, secondPoint);
InverseGeodeticOut inverse;
inverseGeodetic(firstPoint, secondPoint, &inverse);
InverseGeodetic inverse(firstPoint, secondPoint);

也许在这个特殊的例子中,差异太小,不值得讨论,但我想知道这样的结构是否在一般情况下是可以的。

我喜欢你的第二个代码示例,尽管我发现公共构造函数有点令人困惑。特别是如果有其他方法来构造InverseGeodetic。我宁愿使用静态工厂方法来构造它。这样你就可以给方法起一个更有意义的名字:

struct InverseGeodetic
{
    Angle forwardAzimuth;
    Angle backAzimuth;
    double distance;
    static InverseGeodetic FromTwoPoints(const GeoCoordinate &, const GeoCoordinate &);
};
// usage
auto inverse = InverseGeodetic::FromTwoPoints(a, b);

但这可能是我的c#背景。