Understand how to create maintainable programs using comments and naming conventions

Programming Concepts: Comments & Naming Conventions

Why Comments Matter 📝

Comments are like sticky notes that explain what the code does. They help you and others understand the logic without reading every line.

Types of Comments

Comment Type When to Use
Single‑line comment // Short explanations or notes.
Block comment /* */ Longer explanations or commenting out code blocks.
Documentation comment /** */ Generate API docs (Java, Javadoc, etc.).

Naming Conventions: Naming Your Variables, Functions & Classes 🏠

Think of a variable name as the address of a house. A clear address makes it easy to find the house later.

Good Naming Rules

  1. Use descriptive words: totalScore instead of ts.
  2. Start with a letter; no spaces or special characters.
  3. Use camelCase for variables and functions: calculateTotal().
  4. Use PascalCase for classes: StudentRecord.
  5. Keep names short but meaningful.
  6. Use singular nouns for variables, plural for collections.

Bad Naming Examples ❌

Bad Name Why It’s Bad
x Too vague.
student_age Underscore not used in camelCase.
2ndScore Starts with a number.

Example: A Simple Calculator with Comments & Good Naming

// Calculates the sum of two numbers
function addNumbers(firstNumber, secondNumber) {
    // Return the total
    return firstNumber + secondNumber;
}

// Main program
const a = 5;
const b = 10;
const result = addNumbers(a, b);
console.log(`The sum of ${a} and ${b} is ${result}`);

Mathematical Notation in Code

You can use math to describe relationships. For example, the addition operation can be written as $a + b = c$. A function that squares a number is $f(x) = x^2$.

Checklist for Maintainable Code

  • Write clear, concise comments.
  • Follow consistent naming conventions.
  • Keep functions short and focused.
  • Use meaningful variable names.
  • Review code with peers for clarity.

Revision

Log in to practice.

1 views 0 suggestions