While making a struct creates some overhead at run-time, packaging a bunch of frequently-used-together variables can dramatically increase code readability. How do you balance the two? I was just asked to "unroll" a struct that contained 12 variables, which now makes calls to the function header monolithic; it seems poor style and I wanted to know what others thought.
At what point should you collapse many parameters into (e.g.) struct to improve readability in function headers?
4«11. If you have a procedure with ten parameters, you probably missed some.»– 9000Nov 6, 2014 at 20:44
2what programming language are you asking about?– gnatNov 6, 2014 at 20:52
1Is this new code or maintaining legacy code?– mattnzNov 7, 2014 at 2:47
I was asking about general good practices, but the code that sparked the question is C++ (adding new features to a 10-year-old codebase).– BenjinNov 7, 2014 at 18:01
I wouldn't be surprised if it turned out after benchmarking that not using a struct did not make the code any faster. Although many people believe it, just because code is less readable and “more low-level” doesn't mean it will be any faster. In fact, the opposite can be true.– 5gon12ederSep 28, 2016 at 8:44
How many functions do you have that uses those parameters?
If you have 4 functions that all take the same 12 parameters, it's a sign that you probably should bundle those into a cohesive set.
If you have 4 functions that use say... 8 of the parameters, then maybe those 8 should be bundled up.
But this is rather missing a little bit of the point. Bundling into a struct is not your only option. You can also break up the function so that instead of one big function needing 12 parameters, you have 8 more focused ones that need one or two parameters. Smaller functions are easier to test, easier to reuse, easier to write, easier to maintain.
Keep in mind that typically the solution is not always collapsing some of the arguments into a distinct data structure. Most of the times you should split the functions into multiple ones because probably it's the function itself that does multiple things.
I remember Uncle Bob in Clean Code saying there should be at most 2 and only in special cases 3 arguments to a function. This might be very difficult to achieve all the time (take for example functions with timeouts where the timeout and timeunit take 2 arguments).
On the other hand Code Complete is not so rigorous, saying there shouldn't be more than 7 but emphasizing on the fact that in higher-level languages this can be avoided.