How many parameters should a method have?

Asked

Viewed 1,286 times

17

What is the maximum number of parameters a method should have?

When one must consider that there are too many parameters?

And what to do in that case?

Tupiniquim and object-oriented version of the question: design - How Many Parameters are Too Many?

4 answers

17


Never work with absolute numbers. These metrics don’t work. If something like this could be determined compilers would prohibit a higher number.

You can establish something for your project, but it’s silly. Basically this is what is called "good practice", that is, the person establishes a rule because he does not know how to solve the problem conveniently.

It must have as many parameters as necessary.

There are too many parameters when they do not serve the purpose of the method. They are too many when you are passing what you do not need. In general if you are not using a parameter in a given situation there should be a version of it without the parameter. For everything there is exception. We must be pragmatic.

Some people will say that the solution to many parameters is to pass an object. It even makes sense, in fact if you have several related parameters an object there reduces the amount of parameters. But it does bring some benefit?

Will you create an object just to meet this "requirement" of few parameters? And if you do that, you’ve formally decreased the amount of parameters, but the amount of information you’ve entered is the same. What’s the benefit of that? Performance? But it doesn’t cost to build this object? Type less? But type less? Can you handle this object correctly? You know that you can have different semantics, since probably the parameters end up being passed by reference?

What if the object already exists? Great, right? Just pass it. I’m not saying there’s anything wrong with it, if it makes sense, really pass it. If you know how to deal with this situation there is no problem. But who likes to say in general what is good to do will say that this causes excessive coupling (this is the most important thing you should read) since it is almost certain that you will be passing data that is not required for the method.

Here is an addendum on the book Clean Code or everything that Uncle Bob talks about, since there’s an answer (and reproduced in another answer here) in the question that served as inspiration quoting the book. Same with Code Complete. I think every programmer should read these books. But if he doesn’t have a personality, he doesn’t have a very good foundation, that book could butcher a person’s mind. There are incoherent things in the book, there is too much ideology, too much without plausible justification or context. I’m afraid when a fool reads these things and starts blindly following.

Most of the answers there in the question speak of low number and try to justify why this. The problem is that they do not give another solution or the other solution suffers essentially from the same problem. There is no magic. If the problem is complex the solution will be complex. It just cannot be complicated. And often trying to make up the complexity programmers tend to make everything more complicated. They add layers on top of layers without need. Just creating an object just to avoid passing arguments is an unnecessary layer and it doesn’t solve something since it will have to deal with various information in the same way.

There you see that people have a lot of opinion and little real sense. What comes closest to a solution is creating an object to avoid passing multiple parameters, which does not solve something and makes the code more complicated.

Of course, having too many parameters usually shows that the method is doing too many things or the data structure is poorly formulated. But this has to be analyzed case by case. Of course there comes a point where things start to get messy.

I want to point out that no one has given a solution to the case that makes sense for the method to have multiple parameters. No one says that because it depends so much on context and in many cases there is no way to do it to actually solve the problem.

What you can’t do is pass arguments unnecessarily. If the method is doing too much, it probably gets too many parameters. But the problem there is one of responsibility, not over-parameters. Solve the right problem. It’s the same question of number of lines the function should have.

People think things are orthogonal when they are not. They think that changing the argument of place solves some problem, when only the change of place.

  • 1

    And liability problem is a problem of lack of class cohesion, correct?

  • 1

    Not only the class, the method itself. There is no magic rule that defines responsibility. It is a matter of correct collection of requirements, interpretation and proper use of the right mechanisms.

  • I believe that creating a Class (even if private and internal) to group the variables improves the organization and makes the code easier to understand. Once I created a Map with three Maps inside to structure the Data returned by one method and sent to another of the same class, it becomes very confusing to do such a thing.

3

What is the maximum number of parameters a method should have?

The ideal number of arguments for a method is zero (niladic). In followed by one (monadic), followed closely by two (dyadic). Three (triadic) arguments should be avoided whenever possible. More than three (polyadic) requires very special justification - and so should not be used in any way.

And since we always have this "very special justification", there is a certain number of parameters that you say is correct in a method, the question is what you are having, what your method is going to do, what business rules are involved in that process. Here comes your common sense, you may also want to leave parameters unused. Create the method using as few parameters as possible.

I really like the opinion below on the subject:

I hate making rules hard and fast like this because the answer changes not only depending on the size and scope of your project, but I think that even changes to the module level. Depending on what your method is doing, or what the class is supposed to represent, it’s quite possible that 2 arguments is too much and is a symptom of too much coupling. reference

Completion

Varies from project to project, you should seek the correct number of parameters according to your need.

  • And when I have a Webmethod with four or five parameters, how can I reduce this? Passing an object instead of multiple parameters?

  • 2

    Why the ideal number of a method is zero ?

  • @Magichat method with empty parameter, but almost never happens, myself, I do such a few times...

  • 2

    I wonder why he’s considered ideal.

  • @Magichat in the discipline of algorithmic analysis normally seen in the faculty of computer science, we have studied this part of which code is more "light" than the other, so this idea of the ideal amount of parameters being 0 concerns the "lightness" of the code. It is because of this discipline of analyzing algorithms that there is this type of comment, about the "ideal".

  • Ahhhh... It makes sense now.... Since there is a comparison without parameters in the quote...

  • 1

    A method with an empty parameter does not indicate that it is "lightweight". One way this could be justified would be by simplicity and/or ease of use. But I don’t agree.

  • @Georgewurthmann however any byte size is considered in this type of study, they create a whole theory behind, which has been approved in various places in the world for years, and we can only accept the author’s theorem. Until a better foundation arises and the previous idea is discarded.

  • I understand what you mean Philip, but still, that’s not what defines whether it’s "light" or not. A method with 5 parameters int that sums all of them and returns the value is more "heavy" than a method without parameter that performs thousands of loops with calculations of large numbers? But we will not extend here, if you want to better understand my point of view call me in chat.

  • @Georgewurthmann I understood yes colleague, anyway, there is not something 100% in any defined idea in the world, so I am open to other opinions.

Show 5 more comments

3

Metrics are relevant, you should use them!

You should rather make use of "classic" values and base yourself on them to, if they are "disobeyed", do the proper investigation, which may result in the need to adjust the code or in the finding of a false positive. In this sense, if it makes use of Java, I understand that it should make use of tools like Checkstyle and PMD, eventually calibrate the values for a reference value to be used in its context. For example, unless mistaken, Checkstyle suggests at most 7 arguments (default value of this tool).

If it exceeds 7, then it is opportune to investigate. It does not mean that there is an error, nor that the methods with less than 7 are "correct", right? However, there is now a limit that can be automatically checked. Maybe your context sets it to 5 or even 25 (which is larger than the number of registers on an i7), anyway, and in either case, you’ll have some guidance on where to offer additional attention.

0

It is not a rule! As quoted by other friends, it should be take into account the need for work.

Parameter-less:

            var product = new BllProduct
            {
                Code = TxtQueryByCode.Text,
                Size = TxtQueryBySize.Text,
                Reference = TxtQueryByReference.Text,
                Description = TxtQueryByDescription.Text,
                DataPagination = dataPagination
            };

            product.FetchData();

With parameter:

            var product = new BllProduct()
            product.FetchData(TxtQueryByCode.Text, TxtQueryBySize.Text, 
            TxtQueryByRefence.Text, TxtQueryByDescription.Text, OffSetValue, 
            PageSize);

Fechdata() is an interface method and it would be complicated to use this interface in other parts of the system. To do this I have to leave some NULL parameters, since in my case a client has no size searches (SIZE). Or create a search method for each business, but I prefer to reuse the method because I find it simpler.

This is just an example of the context of my work, there are moments that I use some parameters too, for example:

        public static void ShowReport(string path, string reportName, 
        bool isEmbeddedResource, 
        Dictionary<string, object> dataSources)
        {

         var frmReportView = new FrmReportView(path, reportName, isEmbeddedResource,
         dataSources);

         frmReportView.Show();

        }

This method is generic and its main work does not change. I can use it to display any report without the need to modify its parameters for each new report. You see, I passed up to many parameters but the context of the activity was different for each case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.