Reputation: 3081
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.
Upvotes: 0
Views: 485
Reputation: 319
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
}
Upvotes: 1