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 {

Asked by: Cherry644 | Posted: 23-01-2022

Answer 1

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.

Answered by: Dainton279 | Posted: 24-02-2022

Answer 2

public Booking createVehicleBooking(
    Long officeId, 
    Long start, 
    Long end,
    String origin, 
    String destination, 
    String purpose,                 
    String requirements, 
    Integer numberOfPassengers)

throws ServiceException {

Answered by: Alfred532 | Posted: 24-02-2022

Answer 3

I'be inclined to go about it with several objects instead of just one.

So it becomes

public Booking createVehicleBooking(Long officeId, DateRange dates, TripDetails trip)

While DateRange and Trip details contain only the relevant portions of the data. Although arguably the dateRange could be part of the trip while Requirements and Number of Passengers could be remoived from TripDetails and made part of the request.

In fact there are several ways to dice the data but I'd have to say breaking your large list into groups of related parameters and building an object for them will allow a clearer programming style and increase possible reuse.

And remember it is always possible to imbed objects in object thus allowing you to have

public Booking createVehicleBooking(BookingParameters parameters)

While BookingParameters Contains TripDetails and DateRange objects as well as the other parameters.

Answered by: Julian720 | Posted: 24-02-2022

Answer 4

On the calling side I like to simulate named parameters by using comments like this:

    getOfficeId(),      // Long officeId 
    startVariable,      // Long start 
    42,                 // Long end
    getOrigin(),        // String origin 
    "destination",      // String destination 
    "purpose",          // String purpose       
    "requirements",     // String requirements
    3                   // Integer numberOfPassengers

Answered by: Adrian347 | Posted: 24-02-2022

Answer 5

The Google Java Style Guide does not address this directly, but I agree with how they've formatted things in Guava, i.e.


public static <F, T> Collection<T> transform(
    Collection<F> fromCollection, Function<? super F, T> function) {
  return new TransformedCollection<>(fromCollection, function);


public static <T, K extends Comparable<? super K>, V>
    Collector<T, ?, ImmutableRangeMap<K, V>> toImmutableRangeMap(
        Function<? super T, Range<K>> keyFunction,
        Function<? super T, ? extends V> valueFunction) {
  return CollectCollectors.toImmutableRangeMap(keyFunction, valueFunction);

I think the rules are:

  • (Try to keep it on one line if possible)
  • Break after the method name and brace
  • Indent the parameters one extra level to distinguish them from the body

Personally, I prefer to break after each parameter if I have to break at all, i.e.

public static Foo makeFoo(
    Foo foo,
    Bar bar,
    Baz baz)
      throws FooException {

Answered by: Daryl580 | Posted: 24-02-2022

Answer 6

I like the one param per line approach that you're showing. I find it's very easy to scan it visually and see what's present.

I find that when people use something like Guice you often end up with a large number of params and this makes it easier to read.

Answered by: Adelaide297 | Posted: 24-02-2022

Similar questions

methods - Does Java support default parameter values?

I came across some Java code that had the following structure: public MyParameterizedFunction(String param1, int param2) { this(param1, param2, false); } public MyParameterizedFunction(String param1, int param2, boolean param3) { //use all three parameters here } I know that in C++ I can assign a parameter a default value. For example: void MyParameterizedFunction...

api - Why does Java Map<K, V> take an untyped parameter for the get and remove methods?

I ran into a bug in my code where I was using the wrong key to fetch something from a Java map that I believed was strongly typed using Java generics. When looking at the Map Javadocs, many of the methods, including get and remove, take an Object as the parameter instead of type K (for a Map defined as Map). Why is this? Is there a good reason or is it an API design flaw?

methods - Lazy parameter type in Java?

i have a question about parameter passing in Java. Let's say i have a method: public void x(Object o) Let's say i call x(3) and x("abc"). x(3) will take a little bit more time because a new Integer is constructed, since 3 is not an Object. Assuming i can't change the method calls, only the method implementation (and parameter type), is there a way to prevent this Integer construction until...

Giving a Java class name , I want to return its Parameter and Methods

Closed. This question needs details or clarity. It ...

java - How to pass, in parameter, a class and use its methods

As the title presumes, how do I this in Java? What im trying to do is something like this first there is a class public class MyFirstModel() { //standard constructor public MyFirstModel(){ //some lines of codes } //A method public String getvalue() { //do something then return result; } } And the second Model(class)...

java - Call different methods by its parameter

I got an application which should call different methods, based on the params' input. My idea until now is basically, that I create a Switch and call the methods separately by its case. Example: switch (methodName) { case "method1": method1(); break; case "method2": method2(); break; default: System.out.println(methodName + " is not a valid method!"); }

java - Deal with methods that have same parameter types and avoid issues due to pass params in wrong order

When we have a method that accepts arguments of same type we could have the problem of passing the arguments in wrong order i.e. swapped Example int someMethod(int a, int b) And the caller calls the method with someMethod(b,a) instead. I think that there is a design pattern to avoid this issues.Am I right? What is it?

java - Using TestNG parameter values with other methods

I was wondering how I can use the parameters used for TestNG. For example, if i have @org.testng.annotations.Parameters(value = {"browser", "version", "os"}) public static foo() { ... } Can I pass these values somewhere else in the code to be used? ex: System.out.println(value[0]); System.out.println(value[1]); System.out.println(va...

java - How to avoid the need to pass the same parameter to all methods?

In my application, I have service classes with stateless methods operating only in the method parameters. My problem is that many of these methods call external APIs that needs the user and application requesting it. A simple solution is to add these parameters to all service methods, something like: class RequestInformation{ private String user; private String application; } class ...

java - How to access the parameter of one methods to the other method

I have a project to do and i have several classes. In one of the classes i have those two methods: public byte [] getFirstFinalSum(byte [] firstSum) { System.out.println("the first final sum is" +Arrays.toString(firstSum)); return firstSum; } My second Method: public byte [] getSecondFinalSum(byte [] secondSum) { galoaField256 d = new galoaField256 (...

java - How to pass parameter to servlet

How do I pass a parameter from a page's useBean in JSP to a servlet in Java? I have some data in a form that gets passed no problem with a submit button, but no way to send anything else. Please help? Here is my code: &lt;input name = "deleteGameButton" type = "submit" value = "Delete" onclick = "submitToServlet('DeleteGameServlet');"&gt; Here is the corresponding javascript:

java - Optional Parameter in MVEL Functions

Is there a way to get MVEL 2.0 ( ) to work with functions with optional parameters? I would like to be able to eval this: trunc('blahblah',2) but also trunc('blahblah',2,'[...]'); Now i have tried: def trunc(param1,param2,param3) { ... impl ... } That gives an exception if i t...

java - Why null cast a parameter?

This question already has answers here:

generics - Is there a way to pass a Number as a parameter in Java?

I'm allocating an array of T, T extends Number inside a class. I can do it this way: myClass test = new myClass(Double.class, 20); Then the constructor itself: myClass(Class&lt;T&gt; type, size) { array = (T[]) Array.newInstance(type, size); } I'd like to know if it's possible to do it like this: myClass(Number n, size) { array = (T...

java - How do I encode URI parameter values?

I want to send a URI as the value of a query/matrix parameter. Before I can append it to an existing URI, I need to encode it according to RFC 2396. For example, given the input: &amp; value2 I expect the output: Neither nor

java - Detect changing value of object passed as parameter

I'm now working with code that looks like this public String getName(User user) { user.setSth(...); return user.getName(); } I think it's bad practice to change objects passed as parameters. Is there a tool that detects that kind of code? I looked at findbugs, pmd and checkstyle, but could not find any check for this. P.S. sorry for bad example.

java - What name do you use for the parameter in a static variable setter method?

When I write setters for instance methods, I use this to disambiguate between the instance variable and the parameter: public void setValue(int value) { this.value = value; } So, what do I do when value is a class variable (static) instead of a member of an instance? private static int value = 7; public static void setValue(int value) { value = value; // compile fails;...

generics - Is it possible to remove the "Class<T>" parameter from this Java method?

I have a Java method with the following signature: public &lt;T&gt; List&lt;HtmlOptionsComposite&gt; convertToHtmlOptionsCompositeList (List&lt;? extends T&gt; objects, Class&lt;T&gt; clazz, String getValueMethodName, String getDescriptionMethodName, String getDiscontinuedMethodName) { ... } The clazz parameter is required by the method to use refle...

Calling a Java method with the implicit Graphics parameter, like repaint() or accessing the Graphics in a JPanel

When you call repaint(), for example, repaintComponent(Graphics) gets called, and then you can call it from outside the class without the parameter Graphics. I'd like to have a function that takes more parameters I'm using, but I still want to be able to draw with it, so I need to be able to make a call like that (eg repaint() calls repaintComponent(Graphics)) or get access to Graphics to call the function, assumin...

How do I pass a Java object as a parameter to a MATLAB function?

I wrote a Matlab class to implement a database using JDBC and stuff from java.sql. I need to know how many results were in a ResultSet, so I wrote the following Matlab static function: methods (Static) function [numRecords] = numRecords(resultSet) numRecords = 0; if (~isempty(resultSet)) row = resultSet.getRow(); resultSet.beforeFirst(); resul...

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)