Andrii Andriichuk
Andrii Andriichuk

Reputation: 663

Method parameters with same type

I am wondering what is the best practices to write method that takes at least three parameters of the same type. The problem is that you can mix up parameters when using such method. For example

method(int userId, int productId, int weight, int price)

The only solution I see is to use some holder class(maybe with builder pattern used) and passing it as method parameter.

Upvotes: 4

Views: 2367

Answers (4)

Depending on your exact situation, Introduce Parameter Object may be a relevant refactoring option.

More explanations here, from which I quote the below (emphasis mine):

Often you see a particular group of parameters that tend to be passed together. Several methods may use this group, either on one class or in several classes. Such a group of classes is a data clump and can be replaced with an object that carries all of this data. It is worthwhile to turn these parameters into objects just to group the data together. This refactoring is useful because it reduces the size of the parameter lists, and long parameter lists are hard to understand. The defined accessors on the new object also make the code more consistent, which again makes it easier to understand and modify.

Upvotes: 5

user2269148
user2269148

Reputation: 157

For me i think the best practice is to use Data class (java bean ) and but your parameter there with a will named standard and then you use this data class object as parameter.

The disadvantage of this approach is that you are increasing coupling in you system .

Upvotes: 0

dg_no_9
dg_no_9

Reputation: 1013

You can use variable arguments concept in this case.

method(int… ids){
    userid = ids[0];
    productid = ids[1];
}

Upvotes: -4

Kayaman
Kayaman

Reputation: 73528

The best practice is to use clear parameter names (and possibly clarifying them in the Javadoc). If there are too many parameters, a separate object is better.

If the caller of the method can't distinguish between different (well named) parameters, then maybe he shouldn't be calling the method in the first place.

Upvotes: 5

Related Questions