TIL Cleaner data structures
POSTED ON:
This is absolutely beautiful.
I was reading Writing Clean JavaScript and I usually get one or two take-aways.
This had so many take-aways, I had to break it into two posts. This is part 2.
Like any 'clean code', they're kinda rules of thumbs, and opinionated.
I like these opinions.
Structure #
Avoid adding unnecessary contexts #
// Don't ❌
const user = {
userId: "296e2589-7b33-400a-b762-007b730c8e6d",
userEmail: "JDoe@example.com",
userFirstName: "John",
userLastName: "Doe",
userAge: 23,
};
user.userId;
// Do ✅
const user = {
id: "296e2589-7b33-400a-b762-007b730c8e6d",
email: "JDoe@example.com",
firstName: "John",
lastName: "Doe",
age: 23,
};
user.id;
This is pretty straightforward.
If you follow the Don't pattern, you'll end up with user.userFirstName
.
Optional Chaining #
const user = {
email: "JDoe@example.com",
billing: {
iban: "...",
swift: "...",
address: {
street: "Some Street Name",
state: "CA",
},
},
};
// Don't ❌
const email = (user && user.email) || "N/A";
const street =
(user &&
user.billing &&
user.billing.address &&
user.billing.address.street) ||
"N/A";
const state =
(user &&
user.billing &&
user.billing.address &&
user.billing.address.state) ||
"N/A";
// Do ✅
const email = user?.email || "N/A";
const street = user?.billing?.address?.street || "N/A";
const state = user?.billing?.address?.state || "N/A";
Optional chaining is relatively new. I love it, BUT there's some edge-cases with Apple products.
I'd also argue that any time you see multiple if
conditionals, something smells funny.
Better Error handling #
// Don't ❌
try {
// Possible erroneous code
} catch (e) {
console.log(e);
}
// Do ✅
try {
// Possible erroneous code
} catch (e) {
// Follow the most applicable (or all):
// 1- More suitable than console.log
console.error(e);
// 2- Notify user if applicable
alertUserOfError(e);
// 3- Report to server
reportErrorToServer(e);
// 4- Use a custom error handler
throw new CustomError(e);
}
This is a weird one but I really like it!
I'm extra guilty of the Don't version. It does what it needs.
But the second one is so much more useful for production apps.
Avoid using flags as arguments #
// Don't ❌
function createFile(name, isPublic) {
if (isPublic) {
fs.create(`./public/${name}`);
} else {
fs.create(name);
}
}
// Do ✅
function createFile(name) {
fs.create(name);
}
function createPublicFile(name) {
createFile(`./public/${name}`);
}
A flag in one of the arguments effectively means the function can still be simplified.
Related TILs
Tagged: cleancode