Common JS bugs are eminently avoidable in Rust

Kraig McFadden
Rust in Production
Published in
7 min readNov 17, 2023

--

Photo by Clint Patterson on Unsplash

I was working on a Node.js application the other day and came across some code that looked like this:

function formattedName(person) {
if (person.firstName && person.lastName) {
return `${person.firstName} ${person.lastName}`;
} else if (person.firstName && !person.lastName) {
return person.firstName;
} else if (!person.firstName && person.lastName) {
person.lastName;
}

return '';
}

Can you spot the problems with it? I found and fixed at least two (but perhaps there are more that I missed). This code didn’t have a unit test, though if it had I suspect both of these problems would have been caught right away!

The first issue (the one that forced me to look at this code in the first place) is with the person variable. The code checks to make sure that firstName and lastName exist before using them, but it never checks to make sure that person is actually defined. Funny enough, when it's not defined, the function throws an exception. The first fix was to add a guard clause:

function formattedName(person) {
if (!person) {
return '';
}

if (person.firstName && person.lastName) {
return `${person.firstName} ${person.lastName}`;
} else if (person.firstName && !person.lastName) {
return person.firstName;
} else if (!person.firstName && person.lastName)…

--

--

Kraig McFadden
Rust in Production

Staff backend software engineer. Pursuing an MDIV at Reformed Theological Seminary. Princeton 2018 - Electrical Engineering. Opinions are my own.