General coding standards and best practices for web development
Project Status: ProyectoWeb is currently in the planning stage. This guide provides general web development best practices and coding standards that can be applied when development begins.
# Use kebab-case for file namesuser-service.jsapi-client.jsdatabase-connection.js# Or PascalCase for component filesUserProfile.jsxNavigationBar.tsx# Use lowercase for folderscomponents/services/utils/
// 1. External librariesimport React, { useState, useEffect } from 'react';import axios from 'axios';// 2. Internal modules and componentsimport { Button } from '@/components/common';import { UserCard } from '@/components/users';// 3. Utilities and helpersimport { formatDate } from '@/utils/date';import { validateEmail } from '@/utils/validation';// 4. Constantsimport { API_ENDPOINTS } from '@/constants/api';// 5. Types (if using TypeScript)import type { User } from '@/types/user';// 6. Stylesimport styles from './Component.module.css';
// Pure function - no side effectsfunction add(a, b) { return a + b;}// Function with side effects (document clearly)function updateUser(userId, data) { // Side effect: modifies database return database.update('users', userId, data);}
function divide(a, b) { if (typeof a !== 'number' || typeof b !== 'number') { throw new Error('Both arguments must be numbers'); } if (b === 0) { throw new Error('Cannot divide by zero'); } return a / b;}
Provide Meaningful Errors
// Goodif (!user) { throw new Error(`User with ID ${userId} not found`);}// Avoidif (!user) { throw new Error('Error');}
Use Try-Catch Appropriately
async function processData(data) { try { const validated = validateData(data); const processed = await processValidData(validated); return processed; } catch (error) { // Log error for debugging console.error('Data processing failed:', error); // Return user-friendly message throw new Error('Unable to process data. Please try again.'); }}
What the code does (code should be self-explanatory)
Redundant information
// Good: Explains WHY// Using setTimeout instead of setInterval to prevent// overlapping calls if the API response is slowsetTimeout(checkStatus, 5000);// Good: Documents complex logic// Calculate prorated amount based on days used// (total / 30) * daysUsedconst proratedAmount = (subscriptionPrice / 30) * daysActive;// Avoid: States the obvious// Set user nameuser.name = 'John';// Avoid: Commented-out code// const oldImplementation = () => { }
/** * Retrieves a user by their unique identifier * * @param {string} userId - The unique user identifier * @param {Object} options - Optional parameters * @param {boolean} options.includeDeleted - Include deleted users * @returns {Promise<User|null>} The user object or null if not found * @throws {ValidationError} If userId is invalid * * @example * const user = await getUserById('123', { includeDeleted: false }); */async function getUserById(userId, options = {}) { // Implementation}
// Less efficient - O(n²)function hasDuplicates(array) { for (let i = 0; i < array.length; i++) { for (let j = i + 1; j < array.length; j++) { if (array[i] === array[j]) return true; } } return false;}// More efficient - O(n)function hasDuplicates(array) { const seen = new Set(); for (const item of array) { if (seen.has(item)) return true; seen.add(item); } return false;}
Avoid Premature Optimization
Write clear, correct code first
Profile to find actual bottlenecks
Optimize only where it matters
Measure the impact of optimizations
Cache When Appropriate
// Memoization exampleconst memoize = (fn) => { const cache = new Map(); return (...args) => { const key = JSON.stringify(args); if (cache.has(key)) { return cache.get(key); } const result = fn(...args); cache.set(key, result); return result; };};const expensiveOperation = memoize((n) => { // Some expensive computation return n * n;});
# Good feedback"Consider using a Map instead of an object here for better performance when dealing with large datasets. Maps have O(1) lookup time and handle iteration better."# Less helpful feedback"Use Map instead"
When ProyectoWeb moves to implementation, apply these general best practices while following the specific requirements in the project specification document.