- Language specific
function buildUser({ firstName, lastName }) {
return {
firstName,
lastName,
};
);
const myUser = buildUser('Adam', 'Babcock');
const myUser = {
firstName: 'Adam',
lastName: 'Babcock',
};
Pass-through functions are valuable when they provide other utility. Validation, setting default values and type manipulation are all good reasons to have a builder function. Using a pass-through function because you are worried about adding that utility in the future is pre-mature -- when you need it, build it. Otherwise, YAGNI.
The reason a pass-through function is harmful instead of harmless is because every function hop adds readibility and maintenance costs.
class User {
contructor({ firstName, lastName }) {
this.firstName = firstName;
this.lastName = lastName;
}
}
const myUser = new User({ firstName, lastName });
const myUser = {
firstName: 'Adam',
lastName: 'Babcock',
};
In JavaScript, specifically, classes do not provide a lot of inherent value. Similar to a pass-through funciton, a pass-through class isn't doing anything useful and, worse, you can end up with weird side-effects when using object destructoring.
Do not include comments that simply describe language behavior or functions. Assume the person reading your code has knowledge of how the language works.
const {
props: {
user: {
name = 'User',
} = {}, // Destructoring fails if undefined
},
} = this;
// Empty string is falsey
if (!name || name === '') {
return name;
}
const {
props: {
user: {
name = 'User',
} = {},
},
} = this;
if (!name || name === '') {
return name;
}
function areUsersReady(...users) {
const readyStates = ['READY', 'ACTIVATED'];
const isReady = true;
users.forEach((user) => {
if (!readyStates.includes(user.state)) {
isReady = false;
}
});
return isReady;
);
const ready = areUsersReady(userA, userB, userC);
const ans = 'My answer.';
const evt = new Event();
const r = client.get('/yada');
const answer = 'My answer.';
const event = new Event();
const response = client.get('/yada');
Don't abbreviate words that are valid variable names on their own. Consise and accurate naming is valuable but abbreviations take an extra "hop" to mentally process.