简体   繁体   中英

Javascript (Node.js) - Refactoring a long function

I have a function, which is associated with a specific concept "Notifications".

After creating a module "Notifications.js", I have written the following:

function Notifications() {} // No constructor...

Notifications.sendPushNotification = async function (
  title,
  body,
  data,
  badge = undefined,
  sound = "default",
  pushNotificationsTokens
) {
    // Part 1 - 6 lines

    // Part 2 - 10 lines
    
    // Part 3 - 20 lines
}

module.exports(Notifications);

Then, I have also thought to make the code better by doing:

Notifications.sendPushNotification = async function (
  title,
  body,
  data,
  badge = undefined,
  sound = "default",
  pushNotificationsTokens
) {
    part1();
    part2();
    part3();

    function part1() {
       // 6 lines
    }

    function part2() {
       // 10 lines
    }
    
    function part3() {
       // 20 lines
    }
}

module.exports(Notifications);

Here, another question comes to my mind:

Is it a style of code to create classes in independent modules even though they only have static methods? I have seen some GitHub repositories where different developers do this. But... why? Is this way associated to a programming methodology like DDD or something? Is there a difference between doing the code above and this code?

notifications.js

exports.sendPushNotification = async function (
  title,
  body,
  data,
  badge = undefined,
  sound = "default",
  pushNotificationsTokens
) {
    part1();
    part2();
    part3();

    function part1() {
       // 6 lines
    }

    function part2() {
       // 10 lines
    }
    
    function part3() {
       // 20 lines
    }
}

Also, is there a better way to refactor this function? For example, some professional way to pass long list of arguments, using shorter names, or something like that.

Yes it is a good practice to keep your code refactored. I often use async module to handle my async functions. You can find the module at https://caolan.github.io/async/v3/ . If these functions are not async and your functions are dependent on variables. You should use the below strategy for refactoring. This is just a suggestion which I follow.

exports.sendPushNotification = async function (
  title,
  body,
  data,
  badge = undefined,
  sound = "default",
  pushNotificationsTokens
) {
    let var1 = part1(title);
    let var2 = part2(body, var1);
    let var3 = part3(var1, var2);
    
    // ...do some calculations
}


function part1(title) {
   // 6 lines
}

function part2(body, param1) {
   // 10 lines
}

function part3(param1, param2) {
   // 20 lines
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM