Refactoring function signature maintaining backward compatibility

schirrel

Alan Schio

Posted on May 29, 2024

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 😉

💖 💪 🙅 🚩
schirrel
Alan Schio

Posted on May 29, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related