Coding Conventions and Standards - JUCSE49-Mavericks/Smart-Class-Routine-Management-System GitHub Wiki
Rubayed All Islam
Author:1. Naming Conventions
1.1 General:
-
Avoid overly general or wordy names.
- Bad Practice:
var data_structure, my_list, info_map;
- Good Practice:
var userProfile, menuOptions, wordDefinitions;
- Bad Practice:
-
When using camelCase, capitalize all letters of an abbreviation (e.g., HTTPServer).
1.2 Variables:
- Use
camelCase
for variable and function names.- Example:
let examRoll, studentId; let isSubmitted = false;
- Example:
1.3 Constants:
- Use
UPPERCASE_WITH_UNDERSCORES
for constants.- Example:
const MAX_USERS = 100; const API_URL = "https://example.com/api";
- Example:
1.4 Classes:
-
Follow PascalCase for class names.
- Example:
class UserProfile { constructor(name, age) { this.name = name; this.age = age; } }
- Example:
-
Class properties and methods should use camelCase.
1.5 Functions:
- Use
camelCase
for function names.- Example:
function calculateTotalPrice() { // Logic here }
- Example:
1.6 Booleans:
- Prefix boolean variables or methods with
is
.- Example:
let isLoggedIn = false; function isUserActive(userId) { // Logic here }
- Example:
2. Code Layout
2.1 Indentation:
- Use 4 spaces for indentation.
- Example:
function calculateTotalPrice(price, taxRate) { let tax = price * taxRate; let total = price + tax; return total; } if (total > 100) { console.log('High price'); } else { console.log('Reasonable price'); }
- Example:
2.2 Maximum Line Length:
- Limit lines to 80 characters.
- Example:
const totalIncome = baseIncome + investmentIncome - expenses;
- Example:
2.3 Blank Lines:
- Use blank lines to separate sections of code for clarity.
- Example:
// Function 1 function fetchData() { // logic } // Function 2 function processData() { // logic }
- Example:
2.4 Whitespace in Expressions and Statements:
- Avoid extraneous whitespace.
- Correct:
const result = (x + y) * z;
- Wrong:
const result = ( x + y ) * z ;
- Correct:
2.5 Use of Semicolons:
- Always use semicolons to avoid potential pitfalls due to automatic semicolon insertion (ASI).
- Example:
let totalPrice = 100; let taxRate = 0.05; function calculateTax(price, taxRate) { return price * taxRate; }
- Example:
3. Comments and Documentation
3.1 Comments:
-
Use comments to explain complex logic.
- Single-line comments:
// Increment the count by 1 count += 1;
- Single-line comments:
-
Multi-line comments:
/* * This is a longer comment that explains * multiple steps in the code. */
3.2 Documentation Strings:
- Write JSDoc-style documentation for public functions and classes.
- Example:
/** * Calculates the sum of two numbers. * @param {number} a - The first number. * @param {number} b - The second number. * @returns {number} The sum of `a` and `b`. */ function calculateSum(a, b) { return a + b; }
- Example:
4. Declarations and Assignments
4.1 Variable Declarations:
- Use
const
for constants andlet
for mutable variables. Avoid usingvar
.- Example:
const taxRate = 0.05; // Constant value let totalPrice = 100; // Mutable value
- Example:
4.2 Function Declarations:
- Use function declarations where hoisting is required, and arrow functions for shorter syntax and
this
binding in callbacks.- Example:
// Function declaration function greet(name) { return `Hello, ${name}`; } // Arrow function const add = (a, b) => a + b;
- Example:
5. Object and Array Manipulation
5.1 Destructuring:
- Use destructuring for more readable code when working with objects and arrays.
- Example:
const user = { name: 'Alice', age: 25 }; const { name, age } = user; const numbers = [1, 2, 3]; const [first, second, third] = numbers;
- Example:
5.2 Spread Operator:
- Use the spread operator for copying and merging arrays/objects.
- Example:
const userWithAddress = { ...user, address: '123 Main St' }; const numbersCopy = [...numbers];
- Example:
6. Member Access and Modifiers
6.1 Public Members:
- Public properties and methods use standard naming conventions.
- Example:
class User { constructor(name, age) { this.name = name; // public this.age = age; // public } displayInfo() { console.log(`Name: ${this.name}, Age: ${this.age}`); } }
- Example:
6.2 Protected Members (Convention):
- Prefix with
_
to indicate "protected" members.- Example:
class Car { constructor(brand) { this._brand = brand; // "protected" (by convention) } }
- Example:
6.3 Private Members:
- Use
#
to declare private members.- Example:
class BankAccount { #balance = 0; // private deposit(amount) { this.#balance += amount; } }
- Example:
7. Error Handling
7.1 try/catch:
- Use try/catch for error handling.
- Example:
try { let result = riskyOperation(); } catch (error) { console.error('Operation failed', error); }
- Example:
7.2 Promises:
- Handle promises using
.then()
/.catch()
orasync/await
.- Example:
async function fetchData() { try { let response = await fetch('/api/data'); let data = await response.json(); console.log(data); } catch (error) { console.error('Fetching failed', error); } }
- Example:
8. Class Member Order
Member Order:
- Static properties
- Static methods
- Instance properties
- Constructor
- Public instance methods
- Private/Protected methods
Example:
class User {
// 1. Static properties
static MIN_AGE = 18;
// 2. Static methods
static isValidAge(age) {
return age >= User.MIN_AGE;
}
// 3. Instance properties
_balance; // protected (convention)
#password; // private
// 4. Constructor
constructor(name, age, password) {
this.name = name;
this.age = age;
this.#password = password;
this._balance = 0;
}
// 5. Public methods
deposit(amount) {
this._balance += amount;
}
// 6. Private/Protected methods
#resetPassword(newPassword) {
this.#password = newPassword;
}
}
Your JavaScript coding standards are comprehensive and well-structured, covering a wide range of important topics. However, here are a few additional sections that could be valuable based on modern JavaScript practices:
9. Asynchronous Patterns
9.1 Handling Multiple Promises:
- Use
Promise.all()
to handle multiple asynchronous operations in parallel.- Example:
const fetchDataFromMultipleSources = async () => { try { const [data1, data2] = await Promise.all([fetch(url1), fetch(url2)]); const result1 = await data1.json(); const result2 = await data2.json(); console.log(result1, result2); } catch (error) { console.error('Error fetching data', error); } };
- Example:
Promise.race()
:
9.2 Using - Use
Promise.race()
when you need only the fastest promise to resolve or reject.- Example:
Promise.race([promise1, promise2]) .then((result) => console.log(result)) .catch((error) => console.error(error));
- Example:
10. Best Practices for Performance
10.1 Optimize Loops:
-
Avoid unnecessary computations inside loops.
- Example:
// Inefficient for (let i = 0; i < array.length; i++) { if (array[i] % 2 === 0) { console.log(array[i]); } } // Efficient const isEven = num => num % 2 === 0; for (let item of array) { if (isEven(item)) { console.log(item); } }
10.2 Minimize DOM Manipulations:
-
Batch DOM updates to reduce reflows and repaints.
- Example:
// Inefficient for (let item of items) { document.body.appendChild(createElement(item)); } // Efficient const fragment = document.createDocumentFragment(); for (let item of items) { fragment.appendChild(createElement(item)); } document.body.appendChild(fragment);
10.3 Minimize DOM Access:
- Batch DOM reads and writes to improve performance.
- Example:
// Bad: element.style.width = '100px'; element.style.height = '200px'; // Good: element.style.cssText = 'width: 100px; height: 200px;';
- Example:
10.4 Event Delegation:
- Use event delegation to manage event listeners efficiently, especially for dynamically added elements.
- Example:
document.querySelector('#parent').addEventListener('click', (event) => { if (event.target.matches('.child')) { // Handle click on child } });
- Example:
10.5 Throttling and Debouncing:
- Use throttling or debouncing for performance-critical functions such as scroll or resize events.
- Example using lodash:
window.addEventListener('scroll', _.throttle(() => { console.log('Throttled scroll event'); }, 200)); const searchInput = document.getElementById('search'); searchInput.addEventListener('input', _.debounce(() => { console.log('Debounced search input'); }, 300));
- Example using lodash:
11. Security Best Practices
eval()
:
11.1 Avoid - Never use
eval()
as it can make your code vulnerable to injection attacks.- Example:
// Avoid: eval("var a = 10"); // Safe alternative: let a = 10;
- Example:
11.2 Escape User Input:
- Always sanitize and escape user input to prevent cross-site scripting (XSS) attacks.
- Example:
const safeString = userInput.replace(/[<>&'"]/g, function (char) { return ({ '<': '<', '>': '>', '&': '&', "'": ''', '"': '"' }[char]); });
- Example:
12. Modern ES6+ Features
12.1 Template Literals:
- Use template literals for building strings dynamically.
- Example:
const name = 'Alice'; const message = `Hello, ${name}!`; console.log(message); // Output: Hello, Alice!
- Example:
12.2 Default Parameters:
- Use default parameters to assign default values to function arguments.
- Example:
function greet(name = 'Guest') { return `Hello, ${name}`; } console.log(greet()); // Output: Hello, Guest
- Example:
12.3 Rest and Spread Operators:
- Use rest and spread operators for cleaner array and object manipulation.
-
Example (Rest):
function sum(...numbers) { return numbers.reduce((acc, num) => acc + num, 0); } console.log(sum(1, 2, 3)); // Output: 6
-
Example (Spread):
const arr1 = [1, 2, 3]; const arr2 = [...arr1, 4, 5]; const obj1 = { name: 'Alice', age: 25 }; const obj2 = { ...obj1, job: 'Developer' };
-
13. References
-
Airbnb JavaScript Style Guide
A widely adopted and comprehensive JavaScript style guide, known for its practical recommendations and best practices. -
Google JavaScript Style Guide
Google's official JavaScript style guide, focusing on clarity, consistency, and simplicity in JavaScript code. -
MDN Web Docs: JavaScript Guide
Comprehensive and up-to-date documentation on JavaScript, maintained by Mozilla. -
ECMAScript 2022 (ES13)
The latest edition of the ECMAScript language specification, which standardizes JavaScript. -
JSDoc Documentation
Official documentation for JSDoc, a popular tool for generating documentation from JavaScript comments. -
Node.js Best Practices
A community-driven guide to best practices for Node.js development, including error handling, performance, and code structure. -
JavaScript Info
A modern tutorial on JavaScript, covering both fundamental and advanced topics in depth. -
Prettier
A code formatting tool that enforces a consistent style across JavaScript codebases.