Skip to main content
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.

Code Quality Principles

Maintaining consistent code style and quality ensures readability, maintainability, and team collaboration.

General Principles

Clean Code

Write self-documenting, readable code that others can understand

DRY Principle

Don’t Repeat Yourself - avoid code duplication

SOLID Principles

Follow object-oriented design principles

KISS

Keep It Simple - favor simplicity over complexity

Naming Conventions

General Naming Guidelines

Use descriptive, meaningful names:
// Good
const userName = 'John';
const totalPrice = calculateTotal(items);
function getUserById(id) { }

// Avoid
const un = 'John';
const tp = calc(i);
function get(x) { }
Boolean variables should be questions:
const isActive = true;
const hasPermission = false;
const shouldRender = true;
const canEdit = false;

Code Organization

Project Structure

A typical web project structure:
project-root/
├── src/                    # Source code
   ├── components/        # Reusable components
   ├── pages/            # Page components
   ├── services/         # Business logic and API calls
   ├── utils/            # Utility functions
   ├── hooks/            # Custom hooks (if using React)
   ├── types/            # Type definitions
   ├── constants/        # Application constants
   └── styles/           # Stylesheets
├── tests/                # Test files
├── public/               # Static assets
├── docs/                 # Documentation
└── config/               # Configuration files
The actual structure should be determined based on the chosen framework and project requirements.

Import Organization

Organize imports in a consistent order:
// 1. External libraries
import React, { useState, useEffect } from 'react';
import axios from 'axios';

// 2. Internal modules and components
import { Button } from '@/components/common';
import { UserCard } from '@/components/users';

// 3. Utilities and helpers
import { formatDate } from '@/utils/date';
import { validateEmail } from '@/utils/validation';

// 4. Constants
import { API_ENDPOINTS } from '@/constants/api';

// 5. Types (if using TypeScript)
import type { User } from '@/types/user';

// 6. Styles
import styles from './Component.module.css';

Writing Clean Code

Function Guidelines

1

Keep Functions Small

Functions should do one thing and do it well:
// Good - focused function
function calculateTotal(items) {
  return items.reduce((sum, item) => sum + item.price, 0);
}

function applyDiscount(total, discountPercent) {
  return total * (1 - discountPercent / 100);
}

// Avoid - doing too much
function processOrder(items, discount, user) {
  const total = items.reduce((sum, item) => sum + item.price, 0);
  const discounted = total * (1 - discount / 100);
  const tax = discounted * 0.1;
  // ... too many responsibilities
}
2

Use Descriptive Parameters

// Good
function createUser(email, password, firstName, lastName) { }

// Better with object parameter
function createUser({ email, password, firstName, lastName }) { }

// Avoid
function createUser(a, b, c, d) { }
3

Minimize Side Effects

// Pure function - no side effects
function 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);
}
4

Handle Errors Gracefully

async function fetchUser(userId) {
  try {
    const response = await api.get(`/users/${userId}`);
    return { data: response, error: null };
  } catch (error) {
    console.error('Failed to fetch user:', error);
    return { 
      data: null, 
      error: error.message || 'Failed to fetch user' 
    };
  }
}

Error Handling

Defensive Programming

Always validate function inputs:
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;
}
// Good
if (!user) {
  throw new Error(`User with ID ${userId} not found`);
}

// Avoid
if (!user) {
  throw new Error('Error');
}
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.');
  }
}

Version Control Best Practices

Git Workflow

1

Write Clear Commit Messages

Follow conventional commit format:
# Format
<type>(<scope>): <subject>

# Types
feat: New feature
fix: Bug fix
docs: Documentation changes
style: Code style (formatting, missing semi-colons, etc.)
refactor: Code refactoring
test: Adding or updating tests
chore: Maintenance tasks

# Examples
feat(auth): add OAuth2 login support
fix(api): resolve race condition in user data fetch
docs(readme): update installation instructions
refactor(components): simplify UserCard component logic
2

Use Branches

Create branches for features and fixes:
# Feature branch
git checkout -b feature/user-authentication

# Bug fix branch
git checkout -b fix/login-validation-error

# Never commit directly to main/master
3

Keep Commits Focused

Each commit should represent a single logical change:
# Good - focused commits
git commit -m "feat(auth): add login form component"
git commit -m "feat(auth): implement login validation"
git commit -m "feat(auth): add login API integration"

# Avoid - too many changes in one commit
git commit -m "add login, fix bugs, update styles, refactor"
4

Review Before Committing

# Check what will be committed
git status
git diff

# Stage specific files
git add <file1> <file2>

# Commit
git commit -m "feat: add new feature"

Branch Strategy

Use a branching strategy that fits your team size and workflow (Git Flow, GitHub Flow, etc.)
  • main/master: Production-ready code
  • develop: Integration branch for features
  • feature/*: New features
  • fix/*: Bug fixes
  • hotfix/*: Critical production fixes

Code Documentation

Comments Best Practices

Do comment:
  • Complex algorithms or business logic
  • Non-obvious decisions
  • Workarounds or hacks
  • Public APIs and functions
  • Regular expressions
Don’t comment:
  • Obvious code
  • What the code does (code should be self-explanatory)
  • Redundant information

Security Best Practices

Security should be considered throughout the development process, not as an afterthought.

Input Validation

Always validate and sanitize user inputs to prevent injection attacks

Authentication

Use proven authentication libraries and never roll your own crypto

Data Protection

Encrypt sensitive data and never store passwords in plain text

Dependencies

Keep dependencies updated and audit for vulnerabilities regularly

Security Guidelines

// Never expose sensitive information
// Bad
const config = {
  apiKey: 'sk_live_abc123xyz',  // Exposed in code
  password: 'mypassword'
};

// Good - use environment variables
const config = {
  apiKey: process.env.API_KEY,
  dbPassword: process.env.DB_PASSWORD
};

// Always validate and sanitize inputs
function processUserInput(input) {
  // Validate
  if (!input || typeof input !== 'string') {
    throw new Error('Invalid input');
  }
  
  // Sanitize
  const sanitized = input.trim().replace(/[<>]/g, '');
  
  return sanitized;
}

// Use parameterized queries (example with SQL)
// Bad - vulnerable to SQL injection
const query = `SELECT * FROM users WHERE email = '${email}'`;

// Good - parameterized query
const query = 'SELECT * FROM users WHERE email = ?';
database.execute(query, [email]);

Performance Considerations

Choose efficient algorithms and data structures:
// 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;
}
  • Write clear, correct code first
  • Profile to find actual bottlenecks
  • Optimize only where it matters
  • Measure the impact of optimizations
// Memoization example
const 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;
});

Testing Guidelines

Write tests alongside your code, not as an afterthought.

Test Best Practices

  • Write tests that are clear and focused
  • Test behavior, not implementation
  • Use descriptive test names
  • Keep tests independent
  • Mock external dependencies
  • Aim for good coverage of critical paths
// Good test structure
describe('User Service', () => {
  describe('createUser', () => {
    it('creates a user with valid data', async () => {
      // Arrange
      const userData = { email: '[email protected]', name: 'Test' };
      
      // Act
      const user = await createUser(userData);
      
      // Assert
      expect(user).toBeDefined();
      expect(user.email).toBe(userData.email);
    });
    
    it('throws error when email is invalid', async () => {
      // Arrange
      const userData = { email: 'invalid', name: 'Test' };
      
      // Act & Assert
      await expect(createUser(userData)).rejects.toThrow('Invalid email');
    });
  });
});

Code Review Guidelines

Reviewing Code

  • Focus on the code, not the person
  • Explain the reasoning behind suggestions
  • Offer alternatives or examples
  • Acknowledge good work
  • Ask questions rather than making demands
  • Does the code work correctly?
  • Is it easy to understand?
  • Does it follow project conventions?
  • Are there tests?
  • Are there security concerns?
  • Are there performance issues?
  • Is documentation updated?
# 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"

Next Steps

Setup Guide

Learn about development environment setup

Testing

Explore testing strategies and best practices
When ProyectoWeb moves to implementation, apply these general best practices while following the specific requirements in the project specification document.

Build docs developers (and LLMs) love