Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I wrap all params of a method to a wrapper class?

Tags:

java

For example if I have method A, which receives 4 parameters

methodA(String,String,Object,Object)

I think it will look cleaner if I use an object to wrap them.

 methodA(ParamObject)

But I don't know if it have any disadvantage to the performance?

like image 547
Xitrum Avatar asked Sep 11 '25 16:09

Xitrum


1 Answers

Performance is the last thing you should worry about when choosing the signature of your API methods. A much more important concern is readability and maintainability of your API, which could be severely influenced by your decision to group parameters together.

First thing to consider is whether grouping some or all of the parameters makes logical sense. For example, if you have an API that looks like this

public void doSomething(String first, String last, Date dob) {
    ...
}

where the three parameters represent a person's first name, last name, and the day of birth, then changing the API to

public void doSomething(Person p) {
    ...
}

makes perfect sense.

If, on the other hand, the individual parameters are unrelated to each other, except by virtue of being parameters to the same method, then making a class to enclose them makes sense only if you plan to do something else with the invocation parameters, such as storing them for later use, forwarding them to some other method as a single unit, et cetera.

Otherwise, you should keep individual parameters instead of making a parameter-specific class.

like image 81
Sergey Kalinichenko Avatar answered Sep 13 '25 07:09

Sergey Kalinichenko