Recently, I’ve been thinking about few common anti-patterns I tend to see in professional JavaScript projects. Today, I wanted to talk about one of them: no docs.
A lot of more seasoned developers have this obsessed with “self-documenting code.”
And its true that if you write functions that do just one thing and follow logical naming conventions, what a piece of code does can often be pretty apparent.
Looking at the addItemToCart() function below, I can pretty quickly determine that I pass in the ID of the item to add, and it updates the quantity of that item in the cart object.
Self documenting code is more about using sensible names and explicit code.
So
addItemToCartByProductId
instead ofupdateCart
.The idea being, once you get the hang of an API, you can pretty much just guess what the name of the thing you want.
And this applies at all levels.
So
cart[id]
might be better ascart[productId]
becauseid
is ambiguous. Is it the id of the cart? Is that keyed by some user session?Suddenly you are having to maintain a larger scope in your mental model to try and understand what's going on.
You could argue the cart variable could be named better. Or perhaps it's an internal variable, and it gets wrapped in accessor/mutator methods or whatever.
It's the names and syntax that should tell you what things do.
Comments should tell you why complex or obtuse things are being done.
However, code used by multiple people (eg libraries, APIs, open source projects, group/company projects) absolutely need the meta-docunentation. The JSDocs, the readmes, examples, install, config, API overview and all that.
Wikipedia has a good entry on it.
https://en.m.wikipedia.org/wiki/Self-documenting_code
Notably the "objectives" part:
Reduce, not remove.
So the documentation still needs to exist.