Common JS bugs are eminently avoidable in Rust
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)…