Coding Convention and Standard‐2 - JUCSE49-Mavericks/Smart-Class-Routine-Management-System GitHub Wiki

Author: Umma Sumaiya Jahan


1. Naming Principles

1.1 General Guidelines:

  • Choose concise and descriptive names for clarity.

  • Avoid:

    var ds, lst, mp;
    
    
  • Prefer:

    var userProfile, menuItems, dictionaryMap;
    
  • Capitalize entire acronyms in camelCase (e.g., HttpRequest).

1.2 Variable Names:

  • Use camelCase for variable and function names.
    • Example:

      let examRoll, studentIdentifier;
      let hasSubmitted = false;
      

1.3 Constants:

  • Use UPPERCASE_WITH_UNDERSCORES for constants.
    • Example:

      const MAX_USERS = 100;
      const BASE_API_URL = "https://example.com/api";
      

1.4 Class Naming:

  • Class names should follow the PascalCase format.

    • Example:

      class UserProfile {
      constructor(userName, userAge) {
      this.userName = userName;
      this.userAge = userAge;}}
      
  • Method names within classes should use camelCase.

1.5 Function Naming:

  • Use clear, descriptive camelCase for function names.
    • Example:

      function calculateTotalAmount() {
      // Implementation here
      }
      }
      

1.6 Booleans:

  • Prefix boolean variables with is, has, can, etc.
    • Example:

      
      let isLoggedIn = false;
      function hasAccess(userId) {
      // Implementation here
      }
      

2. Code Formatting

2.1 Indentation:

  • Use 6 spaces for indentation to enhance readability.
    • Example:

      function calculateTotal(price, tax) {
        let taxAmount = price * tax;
        let totalAmount = price + taxAmount;
        return totalAmount;
       }
      
       if (totalAmount > 100) {
        console.log('Expensive item');
       } else {
        console.log('Affordable item');
      }
      
      

2.2 Maximum Line Length:

  • Limit lines to 80 characters for better readability.
    • Example:
      const totalIncome = baseIncome
        + additionalIncome
        - expenses;
      
      

2.3 Spacing and Blank Lines:

  • Use blank lines to separate logical blocks of code.
    • Example:
      // Data retrieval function
      function fetchUserData() {
        // logic here
       }
      
      // Data processing function
      function processUserData() {
        // logic here
       }
      
      

2.4 Whitespace in Expressions and Statements:

  • Keep whitespace clean and consistent.
    • Correct:
      const result = (x + y) * z;
      
    • Wrong:
      const result = ( x + y ) * z ;
      

2.5 Use of Semicolons:

  • Always terminate statements with semicolons.
    • Example:
       let totalCost = 100;
       let salesTaxRate = 0.05;
      
        function calculateSalesTax(amount, rate) {
        return amount * rate;
        }
      
      

3. Comments and Documentation

3.1 Commenting Best Practices:

  • Use comments to clarify complex code logic.

    • Single-line comments:
      // Increment the count
      count++;
      
      
  • Multi-line comments:

     /*
    * This section handles user authentication
    * and session management.
    */
    

3.2 Documentation Comments:

  • Utilize JSDoc style for documenting functions and classes.
    • Example:
       /**
      * Adds two numbers together.
      * @param {number} a - The first number.
      * @param {number} b - The second number.
      * @returns {number} The sum of `a` and `b`.
      */
       function add(a, b) {
        return a + b;
       }
      
      

4. Variable and Function Declarations

4.1 Variable Declarations:

  • Use const for constants and let for mutable variables. Avoid using var.
    • Example:
      const TAX_RATE = 0.05; // constant
      let totalPrice = 100;   // mutable variable
      
      

4.2 Function Declarations:

  • Use traditional function declarations when hoisting is required, and arrow functions for concise syntax.
    • Example:
      // Traditional function
       function greet(name) {
        return `Hello, ${name}`;
       }
      
       // Arrow function
       const multiply = (a, b) => a * b;
      
      

5. Object and Array Manipulation

5.1 Destructuring Assignment:

  • Use destructuring for more readable code.
    • Example:
       const user = { name: 'Alice', age: 25 };
       const { name, age } = user;
      
        const numbers = [1, 2, 3];
         const [first, second, third] = numbers;
      
      

5.2 Spread and Rest Operators:

  • Utilize the spread operator for array and object manipulation.
    • Example:
       const updatedUser = { ...user, address: '123 Main St' };
        const numbersCopy = [...numbers];
      
      

6. Member Access and Visibility

6.1 Public Members:

  • Follow standard naming conventions for public properties and methods.
    • Example:
       class User {
        constructor(name, age) {
            this.name = name; // public
            this.age = age;   // public
        }
      
        displayInfo() {
            console.log(`Name: ${this.name}, Age: ${this.age}`);
        }
        }
      
      

6.2 Protected Members (Convention):

  • Use a leading underscore _ to indicate protected members.
    • Example:
        class Vehicle {
        constructor(brand) {
            this._brand = brand; // "protected" (by convention)
        }
        }
      
      

6.3 Private Members:

  • Use # to define private class members.
    • Example:
        class BankAccount {
        #balance = 0; // private
      
         deposit(amount) {
            this.#balance += amount;
         }
       }
      
      

7. Error Handling

7.1 using try/catch:

  • Utilize try/catch for error management.
    • Example:
        try {
        let result = riskyOperation();
        } catch (error) {
        console.error('An error occurred:', error);
        }
      
      

7.2 Promise Handling:

  • Use async/await for cleaner handling of asynchronous operations.
    • Example:
       async function fetchData() {
        try {
            let response = await fetch('/api/data');
            let data = await response.json();
            console.log(data);
        } catch (error) {
            console.error('Fetch failed:', error);
        }
       }
      
      

8. Class Member Organization

Suggested Order:

1. Static Members:

  • Static properties
  • Static methods

2. Instance Members:

  • Private members
  • Protected members
  • Public properties
  • Constructor
  • Public methods

Example:

class User {
      static MIN_AGE = 18;

      static isValidAge(age) {
          return age >= User.MIN_AGE;
      }

      #password; // private member
      _balance;  // protected member

      constructor(name, age, password) {
          this.name = name;
          this.age = age;
          this.#password = password;
          this._balance = 0;
      }

      deposit(amount) {
          this._balance += amount;
      }

      getBalance() {
          return this._balance;
      }

      #checkPassword(input) {
          return this.#password === input;
      }
}


9. Asynchronous Handling Techniques

9.1 Concurrent Promises:

  • Leverage Promise.all() for executing multiple asynchronous requests simultaneously.
    • Example:
        const fetchMultipleSources = async () => {
         try {
          const [response1, response2] = await Promise.all([
              fetch(url1),
              fetch(url2)
          ]);
          const data1 = await response1.json();
          const data2 = await response2.json();
          console.log(data1, data2);
       } catch (err) {
          console.error('Error during data fetch:', err);
       }
       };
      
      

9.2 Fastest Promise Resolution:

  • Utilize Promise.race() when the first promise to resolve is required.
    • Example:
        Promise.race([promiseA, promiseB])
       .then(result => console.log(result))
       .catch(err => console.error('Error:', err));
      
      
      

10. Performance Optimization Tips

10.1 Loop Optimization:

  • Reduce calculations inside loops to enhance performance.

    • Example:
    
    		// Less efficient
                for (let i = 0; i < arr.length; i++) {
                  if (arr[i] % 2 === 0) {
           console.log(arr[i]);
              }
                }
    
              // More efficient
             const isEven = num => num % 2 === 0;
              for (let value of arr) {
               if (isEven(value)) {
               console.log(value);
                }
                   }
    
    

10.2 Limit DOM Manipulation:

  • Group DOM changes to reduce layout thrashing.

    • Example:
    
     	// Less efficient
               for (let elem of items) {
              document.body.appendChild(createElement(elem));
                }
    
              // More efficient
               const frag = document.createDocumentFragment();
                for (let elem of items) {
                 frag.appendChild(createElement(elem));
                   }
               document.body.appendChild(frag);
    
    

10.3 Reduce DOM Access:

  • Group DOM reads/writes together for better performance.
    • Example:
             // Inefficient
           element.style.width = '100px';
           element.style.height = '200px';
      
             // More efficient
             element.style.cssText = 'width: 100px; height: 200px;';
      
      
      

10.4 Event Delegation:

  • Use event delegation to manage event listeners more effectively.

    • Example:
            document.querySelector('#container').addEventListener('click', (event) => {
           if (event.target.matches('.item')) {
          // Handle item click
             }
           });
      
      

10.5 Throttle and Debounce:

  • Implement throttling or debouncing to optimize resource-heavy tasks like scroll or resize events.
    • Example using lodash:
          window.addEventListener('scroll', _.throttle(() => {
        console.log('Throttled scroll');
         }, 200));
      
             const input = document.getElementById('search');
            input.addEventListener('input', _.debounce(() => {
             console.log('Debounced input');
           }, 300));
      
      
      

11. Security Guidelines

11.1 Avoid Using eval():

  • eval() poses security risks and should be avoided.
    • Example:
          // Unsafe:
           eval("var x = 100");
      
          // Safer alternative:
         let x = 100;
      
      

11.2 Escape User Input:

  • Sanitize and escape user-provided data to prevent XSS attacks
    • Example:
          const sanitizedInput = userInput.replace(/[<>&'"]/g, (char) => {
          return ({
          '<': '&lt;',
          '>': '&gt;',
          '&': '&amp;',
          '"': '&quot;',
           "'": '&#39;'
            }[char]);
              });
      
      

12. Modern ES6+ Syntax

12.1 String Interpolation:

  • Leverage template literals to concatenate strings.
    • Example:
         const userName = 'John';
         const message = `Welcome, ${userName}!`;
         console.log(message);  // Output: Welcome, John!
      
      

12.2 Default Parameters:

  • Assign default values to function parameters.
    • Example:
         function greet(name = 'Guest') {
          return `Hi, ${name}`;
          }
      
         console.log(greet());  // Output: Hi, Guest
      
      
      
      
      
      

12.3 Spread and Rest Operators:

  • Simplify object/array handling using spread/rest operators.
    • Example (Rest):

        function sum(...args) {
        return args.reduce((total, num) => total + num, 0);
         }
      
            console.log(sum(1, 2, 3));  // Output: 6
      
      
    • Example (Spread):

         const numbers = [1, 2, 3];
        const extended = [...numbers, 4, 5];
      
          const person = { name: 'John', age: 30 };
           const updatedPerson = { ...person, occupation: 'Engineer' };
      
      

13. References

  1. Comprehensive guide with industry best practices for JavaScript.

  2. Official style guide from Google, emphasizing clean, readable code.

  3. Authoritative JavaScript documentation from Mozilla.

  4. The latest ECMAScript specification outlining JavaScript standards.

  5. Tool for generating documentation from JavaScript comments.

  6. Community-driven guide on best practices for Node.js applications.

  7. In-depth tutorial for mastering modern JavaScript.

  8. Documentation for Prettier, a tool to enforce consistent code formatting.