Search code examples
conventions

Two method arguments or a new class.. for (X and Y cords)


In the book 'Clean Code' by Robert C. Martin, he recommends making use of:

Circle makeCircle(Point center, double radius);

over

Circle makeCircle(double x, double y, double radius);

He basically argues that making a class to avoid using multiple method arguments is preferred.

What is your opinions on this? Please explain to me the benefits, or disadvantages of either.


Solution

  • There are a few reasons for this.

    First, it helps to group parameters meaningfully. In this trivial example, it's immediately obvious that x and y go together, but it might not be as immediately obvious when dealing with a more obscure example.

    Perhaps more importantly, it cuts down on having too many parameters to keep track of meaningfully; once you have a method that takes more than 3 or 4 parameters, it gets more and more cumbersome to keep track of which parameter is which. Binding parameters together in a class or struct helps avoid that.

    Consider this example:

    int HowManyMinutesToAirport(int AirportIdentifier, string AirportName, int PlainIdentifier, string PlainName, int PlaneSpeed, string PlaneCompassDirection);
    

    vs.

    int HowManyMinutesToAirport(Airport airport, Plane plane);