DEV Community

Alan Schio
Alan Schio

Posted on

1 1 1 1 1

Refactoring function signature maintaining backward compatibility

Have you ever see yourself with a function (or method, depending on programming language) that has too many arguments and would be a lot better to switch to a single options/params/item object?
This can be stressfull or painfull depending on all the regressions or usages of this functions. Even sometimes it can be a blind spot to how much that function is being used.

But no fear my friend, Rest Operators are here to save you! 🦸

Bruce from Almighty typing on a keyboard

Imagine you have an add to cart function:

const addItemToCart = (productId, quantity, size) => {
// ommited for god's sake
}
Enter fullscreen mode Exit fullscreen mode

Time (and developers) goes by and we need to add more items to it, but it have so many usages that a refactor will be a hell of a work... After some years this function found itself as

const addItemToCart = (productId, quantity, size, hasPromotion, addedFrom, cartId, someOtherInfo) => {
}
Enter fullscreen mode Exit fullscreen mode

You wish you could change to a simple const addItemToCart = (itemData) => but that will make a simple task grows to a hell of a regressions and files to update, right?

Well let's start a painless refactor:

1 - of course change the functions arguments to be a single one:

const addItemToCart = (itemData) => {
}
Enter fullscreen mode Exit fullscreen mode

2 - let convert this argument to use Rest Operators:

const addItemToCart = (...itemData) => {
}
Enter fullscreen mode Exit fullscreen mode

3 last but not least let's apply conditional validation to use the arguments data:

const addItemToCart = (...itemData) => {
  let item = {};
  if (typeof itemData[0] === 'object') {
    item = itemData[0];    
  else {
    const [
      productId,
      quantity,
      size,
      hasPromotion,
      addedFrom,
      cartId,
      someOtherInfo
    ] = itemData;
    item = {
      productId,
      quantity,
      size,
      hasPromotion,
      addedFrom,
      cartId,
      someOtherInfo
    };
  }
}
Enter fullscreen mode Exit fullscreen mode

And now all old keeps working and you can start write new function call with a prettier code 😉

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay