Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for passing many arguments to method?

Occasionally , we have to write methods that receive many many arguments , for example :

public void doSomething(Object objA , Object objectB ,Date date1 ,Date date2 ,String str1 ,String str2 ) { } 

When I encounter this kind of problem , I often encapsulate arguments into a map.

Map<Object,Object> params = new HashMap<Object,Object>(); params.put("objA",ObjA) ;  ......  public void doSomething(Map<Object,Object> params) {  // extracting params   Object objA = (Object)params.get("objA");  ......  } 

This is not a good practice , encapsulate params into a map is totally a waste of efficiency. The good thing is , the clean signature , easy to add other params with fewest modification . what's the best practice for this kind of problem ?

like image 794
Sawyer Avatar asked Mar 12 '10 11:03

Sawyer


People also ask

What do you do when a function has too many arguments?

There are two techniques that can be used to reduce a functions' arguments. One of them is to refactor the function, making it smaller, consequently, reducing the arguments' number. The Extract Method technique can be use to achieve this goal.

How many arguments do we pass in methods?

This method has four parameters: the loan amount, the interest rate, the future value and the number of periods.

Can a method have multiple arguments?

Multiple ArgumentsYou can actually have your variable arguments along with other arguments. That is, you can pass your method a double, an int, and then a String using varargs.

What is the maximum number of arguments that can be passed to a method in Java?

The number of method parameters is limited to 255 by the definition of a method descriptor (§4.3. 3), where the limit includes one unit for this in the case of instance or interface method invocations.


1 Answers

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.

like image 51
JRL Avatar answered Sep 22 '22 01:09

JRL