Using the first element of an array without additional checks is a common mistake.
function getMyThing() {
const things = getMyThings(...);
return things[0];
}
The code above assumes that there is at least one element in things. Unfortunately, it doesn’t do anything about the situation when this assumption is not true. The following fix (or something similar) is common:
function getMyThing() {
const things = getMyThings();
if (things.length == 0) {
return null;
}
return things[0];
}
Despite the (most likely) intent of getting the only element in the array, the example above fails to handle multiple elements in things. Correct handling of having more than one element is rarely seen. If things are sorted and it’s intentional then there is no problem. This is rarely the case though. Choosing random first element is not the correct or intended behavior in most cases.
I do recommend that if you assume having exactly one element in things and you either think it won’t happen or just not ready to handle this situation – add assertion that would both signal the intent and prevent incorrect execution when this situation happens.
import assert from "node:assert";
function getMyThings() {
return [2,3];
}
function getMyThing() {
const things = getMyThings();
assert.equal(things.length, 1, "Expected to have exactly one thing"); // Throws here
return things[0];
}
console.log(getMyThing());
You can of course to opt for separate checks for length being zero and length being more than one and have more precise error messages… but this is not supposed to happen, right? 🙂
I recommended using assertion above to convey a programming error. Don’t use assertions if:
- If
thingsare input to the program then useif(...) { throw }or consider some input validation framework (like zod) that would eliminate the need for code like above. - If no other part of the code uses assertions then stay consistent with that.
Some languages provide specialized facilities for dealing with exactly one element instead of the more generic assert(). Examples: Enumerable.Single in .NET, the_one in NGS.
This is the first in series of posts about common mistakes in programming. Stay tuned.
Hope this helps. Have a nice $TIME_OF_DAY!