How Many Parameters?
We’re coming to the end of our journey of discovery into function parameters. We’ve learned a lot along the way—How to order parameters, how to group parameters, and what types of parameters to avoid.
Yet, we have not looked into how many parameters we can have on a function. Is there a number that is too large?
Today we’ll find out. Let’s get into it.
I believe the ideal function takes no parameters:
var states = GetStates();
The call to GetStates()
couldn’t be easier to understand. It requires no extra data from us.
One parameter is also fine:
var customer = GetCustomer(id);
What about two parameters?
var orders = SearchOrders(customer, status);
Also fine, but getting busier and cognitive load is on the increase—we need to keep track of a customer
and a status
.
How about three parameters?
var clientSelector = new ClientSelector(config, encrypter, clients);
OK, that’s about the limit right there. Now we are juggling and keeping track of config
, an encrypter
and clients
. The cognitive load has sharply increased from two to three parameters.
Good to know. There it is:
The maximum number of parameters is 3.
Anything more than three parameters, and the function is doing too much. Or the parameters have not been grouped into cohesive objects as we discovered previously.
If a function takes 4 parameters, and grouping those parameters further feels like creating a collection of unrelated things, then this function is doing too much. Pure and simple.
The way to progress here is to break up such a function into smaller, shorter functions that each do less and require fewer parameters to do their work.
Parameters increase cognitive load. Whenever I read a function definition taking more than 3 parameters, I know I am in for pain—especially, if it is a long and protracted function. As a programmer, I need to make mental space for each parameter and local variable. If I see that a function has 7 parameters and another 5 local variables are created and assigned to, then my brain will need to track 12 separate references. Ouch! I am only human, not a computer. That is taxing on my brain. It’d be easy for me to get confused with all these variables. I may have to parse the function definition several times before I understand it.
The Code Coach recommends keeping parameter intake per function to a maximum of 3 for optimal program and programmer health. :D
Leave a Reply
Want to join the discussion?Feel free to contribute!