refactoring

What's the best way to refactor a method that has too many (6+) parameters?


Occasionally I come across methods with an uncomfortable number of parameters. More often than not, they seem to be constructors. It seems like there ought to be a better way, but I can't see what it is.

return new Shniz(foo, bar, baz, quux, fred, wilma, barney, dino, donkey)

I've thought of using structs to represent the list of parameters, but that just seems to shift the problem from one place to another, and create another type in the process.

ShnizArgs args = new ShnizArgs(foo, bar, baz, quux, fred, wilma, barney, dino, donkey)
return new Shniz(args);

So that doesn't seem like an improvement. So what is the best approach?


Solution

  • The best way would be to find ways to group the arguments together. This assumes, and really only works if, you would end up with multiple "groupings" of arguments.

    For instance, if you are passing the specification for a rectangle, you can pass x, y, width, and height or you could just pass a rectangle object that contains x, y, width, and height.

    Look for things like this when refactoring to clean it up somewhat. If the arguments really can't be combined, start looking at whether you have a violation of the Single Responsibility Principle.