I don’t know why, but anytime I see a code example that use’s “foo” or “bar” or any combination of those two, my brain shuts off. I don’t what it is about those two fake words (also, apparently, “baz”, but that one isn’t used as often) but whenever I see them used, I end up just blankly staring at the code example.
Wikipedea doesn’t have much to say about foobar. Apparently the history of it isn’t well known.
I think I have two issues with foobar. One, it feels annoyingly like an inside joke. Two, (more importantly), the words have no context and can therefore mean anything and therefore are not helpful as examples. It’s too abstract. Examples are meant to be concrete - that’s the point of them. First you might read the technical documentation, which often necessarily needs to be very abstract, and you think “hmm okay, an example might help me understand better.” You glance down and you see some example code with more abstraction! That’s not helpful! Examples should something that someone would actually use the code for.
I often revisit the docs on Array.splice at MDN. Here is the technical description of the method:
The splice() method of Array instances changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
I’ve always appreciated how their example uses months.
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// Inserts at index 1
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "June"]
They of course could have used foo, bar, baz, and bum, if they really wanted.
const nonsensewords = ['foo', 'bar', 'baz', 'bum'];
nonsensewords.splice(1, 0, 'far');
// Inserts at index 1
console.log(nonsensewords);
// Expected output: Array ["foo", "far", "bar", "baz", "bum"]
With the months example, you see months, you see that “Feb” is missing, you immediatebly understand what this function does. With the nonsense words, you’ll be able to understand what the function does, but the lack of ceontext means you are forced to grasp the purpose of the function at an abstract level. In this way, the example doesn’t do much more than what the technical description of the function method does.
When writing example for documenting code, always use an example that has some sort of context. Make it a little easier on readers by orienting them. They will be able to understand the purpose of the code that much easier. If you feel the need to provide an abstract example in order to ensure that readers aren’t mislead by the scope of the code, then provide multiple examples. A technical description of the code is necessary, but examples are the best way for readers to understand what the code does.
I’m not the only one who doesn’t like foobar, which is nice to know. This blog post does a better job of making the same aruguments that I do.