Andy Chugunov
Andy Chugunov

Reputation: 31

Functions with many parameters - making them as structs

I'm writing an API for internal needs and so ease of use is one of the top priorities. I wonder if I'm pushing it too far as in the following example.

The function to solve the inverse geodetic problem takes in geocoordinates of two points and calculates distance between them and asimuths (angles) from each of the points to the other.

Ease-of-use-optimised conventional solution might look something like (please don't mind the length of the names, I know there's room for improvement):

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

My question is how reasonable would it be to take it one step further to save user some typing:

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

Perhaps in this particular example the difference is too small to be worth talking about but I wonder if such constructs are okay in general.

Upvotes: 3

Views: 112

Answers (1)

Brandon
Brandon

Reputation: 39212

I like your 2nd code example, though I find the public constructor a bit confusing. Especially if there are other ways to construct an InverseGeodetic. I'd rather use a static factory method to construct it. That way you can give a more meaningful name to the method:

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

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

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

But then that might be my C# background bleeding through.

Upvotes: 2

Related Questions