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

时间:2013-05-29 20:09:51

标签: c++ coding-style

我正在为内部需求编写API,因此易用性是首要任务之一。我想知道我是否将它推得太远,如下例所示。

解决逆大地测量问题的函数采用两点的地理坐标,并计算它们之间的距离以及从每个点到另一个点的asimuths(角度)。

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

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

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

1 个答案:

答案 0 :(得分:2)

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

struct InverseGeodetic
{
    Angle forwardAzimuth;
    Angle backAzimuth;
    double distance;

    static InverseGeodetic FromTwoPoints(const GeoCoordinate &, const GeoCoordinate &);
};

// usage
auto inverse = InverseGeodetic::FromTwoPoints(a, b);

但那可能是我的C#背景流血。

相关问题