Developing on Staxmanade

JavaScript - Refactoring too many function params

(Comments)

A code smell that can creep into your JavaScript codebase and quickly make the code difficult to follow is when a function has too many parameters.

EX:

myFunction("val1", 1, true, false, false, true);

Looking at the above, we can sort of tell that the first param is some string, maybe we can even tell what it's purpose is, the second a number maybe we even know why if we understand the codebase. But the booleans that follow? What are those representing? How do you know you're providing the right value for the right argument?

One approach is to refactor those parameters into variable names to help give them meaning.

EX:

var firstName = "val1";
var age = 1;
var isCool = true;
var isHungry = false;
var isSleeping = false;
var isHappy = true;
myFunction(firstName, age, isCool, isHungry, isSleeping, isHappy);

Now at least when we look at each parameter we can see it's name and that helps give some context of what it represents.

But as this parameter list grows it can be difficult to maintain. We could argue it's already too long.

What if you have to add a parameter in the middle?

How can you be sure all the callers get updated correctly?

Another approach would be to refactor this list of parameters into an object of properties.

This comes with some benefits like, you can add/remove properties without worrying about parameter ordering, as long as they can be optional and have solid defaults.

One cool thing I found with ES6 destructuring and enhanced object literals is if our function definition AND our caller follow a similar pattern. Meaning the variable names used in the caller are the same as the parameter names within the function.

EX:

function myFunction(firstName, age, isCool, isHungry, isSleeping, isHappy) {}

//**

var firstName = "val1";
var age = 1;
var isCool = true;
var isHungry = false;
var isSleeping = false;
var isHappy = true;
myFunction(firstName, age, isCool, isHungry, isSleeping, isHappy);

To refactor this we can simply have the caller pass an object, and have the function use destructuring of that object. It simply becomes.

function myFunction({firstName, age, isCool, isHungry, isSleeping, isHappy}) {}
var firstName = "val1";
var age = 1;
var isCool = true;
var isHungry = false;
var isSleeping = false;
var isHappy = true;
myFunction({firstName, age, isCool, isHungry, isSleeping, isHappy});

This is cool because it's simple, requires very little work, and now we can gain the benefits of using an object instead of an ordered set of parameters.

This opens the door to quit a few other organization options.

Happy Cleanup!

Comments