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..*/ }
Multiple Arguments That is, you can pass your method a double, an int, and then a String using varargs. It might seem silly to have multiple arguments in a method that already takes multiple arguments. Consider this, the varargs piece can only accept one data type.
The parameter list of a method specifies the types of arguments to which the method is applicable, and declares local bindings to which those arguments will be bound during the execution of the body of the method. It may also declare the return value types of the method.
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.
public Booking createVehicleBooking( Long officeId, Long start, Long end, String origin, String destination, String purpose, String requirements, Integer numberOfPassengers) throws ServiceException { /*..Code..*/ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With