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

maximum number of parameters...

 
ankur rathi
Ranch Hand
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

What is the maximum number of parameters are recommended for a method???

I have a method that takes 6 parameters, is it OK to pass 6 parameters or we should pass a map or we should pass a object that has all 6 parameters...

Please comments..

Thanks.
 
Stuart Gray
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I guess you could use an object depending on how the parameters are related to one another. I'm sure others can give better advice on that.

However, remember that as of JDK 1.5 you can use the 'varargs' feature to pass (almost) as many parameters as you like to a method and have them treated like an array. Of course, the parameters will have to be of the same type though.
 
Jean-Sebastien Abella
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
6 can be ok if you really need it. But you should stay below 5 so 0,1,2,3,4.

I would also add to try to have a standard in the way you order those arguments and try to mix the type it will be easier to remember the syntax.
But this is just my standard.
 
Sathya Srinivasan
Ranch Hand
Posts: 379
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is not clearcut number for the max. number of arguments - only rules of thumb. I try to limit my methods to not more than 3 arguments (4 in rare cases). If you have too many arguments, you might be doing too many things in that method.

Remember the "Single Responsibility Principle". Each software artifact should do one, and only one job well.

I do tend to get a bit lenient on the private methods though (may be upto 6 parameters), especially if it reuses some piece of code and since they are not seen by other classes.

In general, if you see yourself using more than 3-4 arguments in a public method, consider defining a data structure (value object) that can be passed around or rethink your design to eliminate that need.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic