Naming and Commenting

Topic

Naming and Commenting

Topic Progress:

Naming Things

It’s important to name things by what they do. It’s too easy to just call a variable or function a, or b and then two weeks down the road when you look at your code again, it doesn’t make sense.

Try giving your variables more useful names, for example, if you’re remembering the player’s name, you can use playerName to as a variable name.

KISS Commenting

“KISS” stands for Keep It Short and Simple. This is the approach you should take with commenting. Comments are usually kept for debugging and explaining tricky to understand code—or to explain the overarching goal of the code.

// this functions clears the screen
function clearScreen() {
  // we do this by setting all the pixels to black
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      setPixel(x, y, BLACK);
    }
  }
}

You also don’t need to comment every line of code and explain it in English since what it means is clear to everyone who knows to read the programming language.

function funky() {
  let x = "a";          // assign "a" to x
  let y = doStuff(x);   // do stuff to x to get y
  return y;             // return y
}

Here is some of the best commenting advice I have ever read.

Comments are good, but there is also a danger of over-commenting. NEVER try to explain HOW your code works in a comment: it’s much better to write the code so that the working is obvious, and it’s a waste of time to explain badly written code.

Generally, you want your comments to tell WHAT your code does, not HOW. Also, try to avoid putting comments inside a function body.

You can make small comments to note or warn about something particularly clever (or ugly), but try to avoid excess. Instead, put the comments at the head of the function, telling people what it does, and possibly WHY it does it.

from Chapter 8: Commenting, Linux kernel coding style

Grouping

In JavaScript, you can group similar variables into an object as discussed in part 1. This way you don’t have to create different variables for each player, but instead just use one.

// DON'T: make separate variables
let playerName = prompt();
let playerAge = parseInt(prompt());
let playerFavouriteColour = prompt();
let playerHobby = prompt();

// DO: make an object
let player = {
  name: prompt(),
  age: parseInt(prompt()),
  favouriteColour: prompt(),
  hobby: prompt()
};

This will make it easier for when you’re sending data back and forth.

/*
 * using independent variables
 */

// make a function
function printPlayer(name, age, favouriteColour, hobby) {
  console.log("Name: " + name);
  // do more stuff
}

// use the function
printPlayer(playerName, playerAge, playerFavouriteColour, playerHobby);


/*
 * using objects
 */

// make a function
function printPlayer(player) {
  console.log("Name: " + player.name);
  // do more stuff
}

// use the function
printPlayer(player1);

@

Not recently active