Best practice for passing many arguments to method? Best practice for passing many arguments to method? java java

Best practice for passing many arguments to method?


In Effective Java, Chapter 7 (Methods), Item 40 (Design method signatures carefully), Bloch writes:

There are three techniques for shortening overly long parameter lists:

  • break the method into multiple methods, each which require only a subset of the parameters
  • create helper classes to hold group of parameters (typically static member classes)
  • adapt the Builder pattern from object construction to method invocation.

For more details, I encourage you to buy the book, it's really worth it.


Using a map with magical String keys is a bad idea. You lose any compile time checking, and it's really unclear what the required parameters are. You'd need to write very complete documentation to make up for it. Will you remember in a few weeks what those Strings are without looking at the code? What if you made a typo? Use the wrong type? You won't find out until you run the code.

Instead use a model. Make a class which will be a container for all those parameters. That way you keep the type safety of Java. You can also pass that object around to other methods, put it in collections, etc.

Of course if the set of parameters isn't used elsewhere or passed around, a dedicated model may be overkill. There's a balance to be struck, so use common sense.


If you have many optional parameters you can create fluent API: replace single method with the chain of methods

exportWithParams().datesBetween(date1,date2)                  .format("xml")                  .columns("id","name","phone")                  .table("angry_robots")                  .invoke();

Using static import you can create inner fluent APIs:

... .datesBetween(from(date1).to(date2)) ...