Documentation is for yourself
A lot of developers are really into self-documenting code: codes whose name and purpose is so obvious that it doesn’t need any comments or documentation around it.
Here, it’s pretty obvious that the getCurrentUser() function is going to return the current active user.
function getCurrentUser () {
let token = getUserToken();
let user = db.get(`session_${token}`);
return user;
}
But… but! If you have ADHD, your working memory is kind of shit.
What seems obvious today or in the moment may not be in the future. One function in isolation is easy to remember. Many functions working together? It gets messy!
For example, imagine you have another function called getUser().
function getUser (username) {
let user = db.get(`user_${username}`);
return user;
}
Look at this one, you can probably tell that you need to pass in a username, and you’ll get back a user record from the database.
But you also might not remember that there’s already a getCurrentUser() function if you need the currently active one, which might lead to you cobbling together different functions when a helper function already exists…
let token = getUserToken();
let username = getUsernameFromToken(token);
let user = getUser(username);
A few years ago on Twitter, Dr. Kate Compton shared this delightful little one-sentence gem about how to write good comments…
Programming pro tip: In your comments, write what you did and why, record your level of petulance (REALLY) and the StackOverflow link that made you realize something
Basically, any information that adds context about not just what the function does, but why it does it and other important stuff you might want to know.
Imagining that our two previous functions were in separate places in the code base, you might do something like this…
/**
* Returns a user record for the currently active user
* @return {Object} The user record
*/
function getCurrentUser () {
let token = getUserToken();
let user = db.get(`session_${token}`);
return user;
}
/**
* Returns the user record for a specific username
* NOTE: for the currently active user, use the getCurrentUser() function instead
* @param {String} username The username of the user
* @return {Object} The user record
*/
function getUser (username) {
let user = db.get(`user_${username}`);
return user;
}
This is useful for other developers, too, of course!
But it’s astounding how much you’ll forget about a code base if you don’t look at it for a few months.