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 ?
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.
This method has four parameters: the loan amount, the interest rate, the future value and the number of periods.
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.
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.
In Effective Java, Chapter 7 (Methods), Item 40 (Design method signatures carefully), Bloch writes:
There are three techniques for shortening overly long parameter lists:
For more details, I encourage you to buy the book, it's really worth it.
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