Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the maximum number of parameters to be passed ?

 
Amandeep Singh
Ranch Hand
Posts: 850
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a theoretical question, what is the maximum number of parameters to be passed is considered a good practice.

In my method i am passing 5 parameters. I am moving forward to add more, so total will be 7 parameters.

Well i have a solution to this problem. To make a Map and put 3 parameters inside it. and pass it as a 1 parameter.

can you guys share your expertise ?
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13071
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually I use the Map solution all the time. It has the great advantage of not breaking when you add more functionality.

Bill
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65115
89
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I will also sometimes define a bean to abstract a complex set of arguments -- has a bit more structure than a Map. But I like the Map solution as well (a habit from JavaScript). I'll use whichever seems to make the most sense within a scenario.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tend to make a bean, often with "fluent"-style methods. I use maps sometimes, but find the lack of type safety (depending on what you're doing, of course) a little bothersome.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65115
89
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David Newton wrote:I use maps sometimes, but find the lack of type safety (depending on what you're doing, of course) a little bothersome.

That. And the fact that both sides need to agree on the keys. But sometimes, a map just feels right.
 
David Sharpe
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I write a method that has more than three parameters, I usually get suspicious that I'm either not decomposing the problem, or not encapsulating my solution.

For example:
void recordSale(Sale sale, int day, int month, int year) {...}

Should probably be:
void recordSale(Sale sale, Date date) {...}

Or potentially even just:
void recordSale(Sale sale) {...}

Like most best practices, any answer to your question will really only be a heuristic for good design. Sometimes, one parameter is too many.

I worry that the Map solution is easily misused:
void recordSale(Sale sale, Map date) {...}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic