0

is it good work that design a method that have more parameter(for example five parameter) in java?

 public List<Node> loadByParentAndNeighbor(Map<String, Object> properties, String parentLabel, String neighborLabel, String parentRelation, String neighborRelation) {
     return null;
 }

2 Answers2

1

case -1 : If the parameters are unrelated , then they cannot be put into a single container (like a list) and passed to this method. So it would be acceptable to have a method with several parameters.

case-2 : If the parameters are related.For example if an Object has 10 fields, and 5 of them are being passed to a method, then it would be cleaner and more readable to pass the object itself (rather than 5 of its parameters.)

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • in this method that I post it , parentLabel and parentRelation is related , neighborLabel and neighborRelation is related. can I put them in map and method would be have three map parameter. is it good??? – user3807246 Jul 16 '14 at 06:43
  • @user3807246 - This is more of a design issue. You should *not* pass more than what the method needs (technically..) unless it simplifies *something* significantly. How are the fields related? – TheLostMind Jul 16 '14 at 06:47
0

Too many parameters is considered bad practice and should be avoided where possible.

The reason is that if you have the following function:

public void addUser(String username, String firstname, String lastname)

It is very easy to confuse the parameters when calling the functions (was the first parameter firstname or username?).

addUser("johnd", "John", "Doe");

To solve this, it is always best to group parameters when you get too many. For instance into a class called Name with a member firstname and lastname.

Name name = new Name("John", "Doe");
addUser("johnd", name);

This problem also arises with fewer parameters (as in my example) but with more, especially when there are many of the same type, it gets gradually worse.

Thirler
  • 20,239
  • 14
  • 63
  • 92