abarax abarax - 4 months ago 8
Java Question

How to format methods with large parameter lists

I have never seen a way to do this nicely, i would be interested in seeing how others do it. Currently i format it like this:

public Booking createVehicleBooking(Long officeId,
Long start,
Long end,
String origin,
String destination,
String purpose,
String requirements,
Integer numberOfPassengers) throws ServiceException {
/*..Code..*/
}

Answer

A large set of parameters like this is often (but not always) an indicator that you could be using an object to represent the parameter set. This is especially true if either:

  • There are several methods with similar large parameter sets, that can be replaced with a single method taking a parameter object.

  • The method is called create...

So your above code could become (pardon my C++, I'm a Java developer):

class BuildVehicleBooking {
    Long officeId;
    Long start;
    Long end;
    String origin;
    String destination;
    String purpose;             
    String requirements;
    Integer numberOfPassengers;

    Booking createVehicleBooking () throws ServiceException { ... }
}

This is the Builder Pattern. The advantage of this pattern is that you can build up a complex set of parameters in pieces, including multiple variations on how the parameters relate to each other, and even overwriting parameters as new information becomes available, before finally calling the create method at the end.

Another potential advantage is that you could add a verifyParameters method that checked their consistence before you go as far as creating the final object. This is applicable in cases where creating the object involves non-reversible steps, such as writing to a file or database.

Note that, as with all patterns, this doesn't apply in every case and may not apply in yours. If your code is simple enough then this pattern may be over-engineering it. If the code is getting messy, refactoring into this pattern can be a good way to simplify it.

Comments