Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any workaround for functions having large number of arguments?

There is a function that I call once in a day :

new SubmitLogs().mail(IP, date_time_UTC, date_time_IST , pageVisited , userCountry , userRegion , city , userAgent);

The function arguments keep on growing. Initially it was like :

new SubmitLogs().mail(IP, date_time_UTC, userAgent);

and now it has 5 more arguments. It is expected to contain more arguments in a week.Now I do not like this.Maintaining functions with so many arguments doesn't seem to be a good thing to me. Is there any work around for this ? I will never want to send some 50 arguments to a function if it keeps growing. What the call does is email the details in the argument with a short message and a short subject.

like image 723
saplingPro Avatar asked Sep 13 '12 10:09

saplingPro


People also ask

What do you do when a function has too many arguments?

Many times, we tend to add too many parameters to a function. But that's not the best idea: on the contrary, when a function requires too many arguments, grouping them into coherent objects helps writing simpler code.

Can a function have too many arguments?

For developers, it is important to consider that having too many arguments tends make the function excessively complex. This increases development time as it becomes more difficult for others to use, and understand the offending sections of code.

What is the maximum number of arguments a function can take?

1 Answer. To explain: C++ allows maximum number of 256 arguments in a function call.


1 Answers

You have two options really

  1. Try and group some of the parameters together into an object. This will encapsulate similar things together. For example you could put userRegion, userCountry and city together into a Location object

  2. Alternatively the Builder pattern is good. Josh Bloch's Effective Java has a good chapter on it.

like image 199
RNJ Avatar answered Sep 28 '22 01:09

RNJ