testers.ai

Code Quality Issues Demonstration

⚠️ Important Notice

This page contains intentional code quality issues for testing and educational purposes only. These examples demonstrate common code quality problems like code smells, technical debt, poor structure, and maintainability issues. Always follow code quality best practices and use linting tools in production.

Code Quality Issues

The following examples demonstrate common code quality problems:

1. Magic Numbers Magic Numbers

Hardcoded numbers without explanation:

// VIOLATION: Magic numbers if (user.age > 18 && user.score > 70) { grantAccess(); } setTimeout(() => { refreshData(); }, 86400000); // What is 86400000? // Hard to understand, maintain, and change

Problem: Numbers like 18, 70, and 86400000 have no meaning without context.

What if the age requirement changes? What if the timeout needs adjustment?

2. Long Functions Complexity

Functions that do too much:

// VIOLATION: Long function doing everything function processUser(user) { // Validate user if (!user) return; if (!user.email) return; if (!user.email.includes('@')) return; if (user.email.length < 5) return; // Format data user.email = user.email.toLowerCase().trim(); user.name = user.name.trim(); user.name = user.name.charAt(0).toUpperCase() + user.name.slice(1); // Save to database const db = connectDatabase(); const query = `INSERT INTO users (email, name) VALUES ('${user.email}', '${user.name}')`; db.execute(query); // Send email const emailService = new EmailService(); emailService.send(user.email, 'Welcome!', 'Thanks for joining'); // Log activity console.log('User created:', user.email); analytics.track('user_created', { email: user.email }); // Update cache cache.set(`user:${user.email}`, user); return user; } // 50+ lines, multiple responsibilities

Problem: Function has 50+ lines, 5+ responsibilities, High complexity

Hard to test, maintain, and understand

3. Deeply Nested Code Nesting

Too many levels of nesting:

// VIOLATION: Deep nesting function processOrder(order) { if (order) { if (order.items) { if (order.items.length > 0) { for (let i = 0; i < order.items.length; i++) { if (order.items[i].price) { if (order.items[i].price > 0) { if (order.items[i].stock > 0) { // Process item processItem(order.items[i]); } } } } } } } } // 7 levels of nesting - hard to read

Problem: 7 levels deep - Pyramid of doom

Hard to read, test, and maintain

4. Duplicate Code DRY

Same code repeated multiple times:

// VIOLATION: Duplicate code function validateEmail(email) { if (!email) return false; if (!email.includes('@')) return false; if (email.length < 5) return false; return true; } function validateUsername(username) { if (!username) return false; if (!username.includes('@')) return false; if (username.length < 5) return false; return true; } function validatePassword(password) { if (!password) return false; if (!password.includes('@')) return false; if (password.length < 5) return false; return true; } // Same validation logic repeated 3 times

Problem: 3x duplication - Violates DRY principle

Changes need to be made in 3 places

5. Poor Variable Names Naming

Unclear or misleading variable names:

// VIOLATION: Poor naming const x = getUserData(); const temp = processData(x); const stuff = formatStuff(temp); const result = doSomething(stuff); function calc(a, b, c) { return a * b + c; } const d = new Date(); const n = d.getTime(); // Names don't explain purpose

Problem: Variables like x, temp, stuff don't explain what they contain

Code is self-documenting only if names are meaningful

6. Commented-Out Code Dead Code

Old code left commented instead of removed:

// VIOLATION: Commented-out code function calculateTotal(items) { // const tax = items.reduce((sum, item) => sum + item.price * 0.1, 0); // const subtotal = items.reduce((sum, item) => sum + item.price, 0); // return subtotal + tax; // New implementation return items.reduce((sum, item) => sum + item.price * 1.1, 0); // TODO: Add discount logic // if (user.hasDiscount) { // return total * 0.9; // } } // Dead code clutters the file

Problem: Dead code - Confusing and clutters codebase

If code is needed, use version control. If not, delete it.

7. God Objects/Classes Coupling

Classes or objects that know too much:

// VIOLATION: God class class UserManager { createUser() { } updateUser() { } deleteUser() { } sendEmail() { } processPayment() { } generateReport() { } exportData() { } validateInput() { } formatData() { } logActivity() { } updateCache() { } syncDatabase() { } // 50+ methods, too many responsibilities } // Violates Single Responsibility Principle

Problem: 12+ methods, Multiple responsibilities

Hard to test, maintain, and understand

8. Inconsistent Code Style Style

Mixed coding styles in same codebase:

// VIOLATION: Inconsistent style function getUserData() { return fetch('/api/user'); } const getOrderData = () => { return fetch('/api/order'); } async function getProductData() { return await fetch('/api/product'); } // Mix of function declarations, arrow functions, async/await // Inconsistent indentation, spacing, naming conventions

Problem: Inconsistent patterns - Hard to read and maintain

Team members use different styles

9. No Error Handling Errors

Code that doesn't handle errors:

// VIOLATION: No error handling function loadUserData(userId) { const user = database.getUser(userId); const orders = database.getOrders(userId); const preferences = database.getPreferences(userId); return { user, orders, preferences }; } // What if database fails? What if userId is invalid?

Problem: No try/catch, No validation

Code will crash on any error

10. Hardcoded Values Configuration

Configuration values hardcoded in code:

// VIOLATION: Hardcoded values function connectToDatabase() { return new Database({ host: 'localhost', port: 5432, username: 'admin', password: 'password123', database: 'production_db' }); } const apiUrl = 'https://api.example.com/v1'; const maxRetries = 3; const timeout = 5000; // Values should be in config files

Problem: Hardcoded credentials, No environment config

Can't change without code changes, security risk

11. Global Variables Scope

Excessive use of global variables:

// VIOLATION: Global variables var currentUser = null; var isLoggedIn = false; var cartItems = []; var apiKey = 'abc123'; function addToCart(item) { cartItems.push(item); updateUI(); } function updateUI() { if (isLoggedIn && currentUser) { // Uses global variables } } // Global state is hard to track and debug

Problem: Global state - Hard to track, test, and debug

Variables can be modified from anywhere

12. Long Parameter Lists Parameters

Functions with too many parameters:

// VIOLATION: Too many parameters function createUser(firstName, lastName, email, phone, address, city, state, zip, country, birthDate, gender, role, department, salary, startDate, manager, notes) { // 17 parameters - impossible to remember order return { firstName, lastName, email, phone, address, city, state, zip, country, birthDate, gender, role, department, salary, startDate, manager, notes }; } // Hard to call, easy to make mistakes

Problem: 17 parameters - Hard to use and maintain

Easy to pass parameters in wrong order

13. No Type Checking Types

No validation of input types:

// VIOLATION: No type checking function calculateTotal(items) { return items.reduce((sum, item) => sum + item.price, 0); } calculateTotal('not an array'); // Crashes calculateTotal([{ price: 'not a number' }]); // Returns NaN calculateTotal(null); // Crashes // No validation of input types

Problem: No type validation - Runtime errors

TypeScript or runtime checks would prevent this

14. Tight Coupling Coupling

Components too dependent on each other:

// VIOLATION: Tight coupling class OrderService { processOrder(order) { const db = new MySQLDatabase(); const email = new GmailService(); const payment = new StripePayment(); const cache = new RedisCache(); db.save(order); email.send(order.user.email, 'Order confirmed'); payment.charge(order.total); cache.set(`order:${order.id}`, order); } } // Directly instantiates dependencies - hard to test or change

Problem: Tight coupling - Hard to test, change, or reuse

Can't swap implementations without code changes

15. No Documentation Documentation

Code without comments or documentation:

// VIOLATION: No documentation function process(data) { const result = []; for (let i = 0; i < data.length; i++) { if (data[i].status === 1 && data[i].value > 100) { const temp = data[i].value * 0.15; result.push({ id: data[i].id, tax: temp, total: data[i].value + temp }); } } return result; } // What does this function do? What are the parameters? Return value?

Problem: No comments, No JSDoc

Future developers won't understand the code

16. Code Smells Smells

Various code smells:

// VIOLATION: Multiple code smells class User { constructor() { this.data = {}; } setData(key, value) { this.data[key] = value; } getData(key) { return this.data[key]; } // Feature envy - uses another class's methods excessively processOrder(order) { return order.calculateTotal() + order.getTax() - order.getDiscount(); } // Data clump - related data passed separately updateProfile(name, email, phone, address) { // Should be an object } // Long parameter list createReport(type, format, startDate, endDate, includeDetails, sortBy, filter) { // 7 parameters } }

Problem: Feature envy, Data clumps, Long parameters

Multiple code quality issues in one class

Code Quality Best Practices

The following examples demonstrate proper code quality practices:

1. Named Constants Constants

// Compliant: Named constants const MINIMUM_AGE = 18; const MINIMUM_SCORE = 70; const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000; if (user.age > MINIMUM_AGE && user.score > MINIMUM_SCORE) { grantAccess(); } setTimeout(() => { refreshData(); }, MILLISECONDS_PER_DAY); // Clear, maintainable, self-documenting

✓ Benefits: Easy to understand, change in one place, self-documenting

2. Small, Focused Functions Functions

// Compliant: Small, focused functions function validateEmail(email) { return email && email.includes('@') && email.length >= 5; } function formatUserEmail(user) { return user.email.toLowerCase().trim(); } function formatUserName(user) { const trimmed = user.name.trim(); return trimmed.charAt(0).toUpperCase() + trimmed.slice(1); } function saveUserToDatabase(user) { const db = connectDatabase(); const query = buildInsertQuery(user); return db.execute(query); } function processUser(user) { if (!validateEmail(user.email)) { throw new Error('Invalid email'); } const formattedUser = { ...user, email: formatUserEmail(user), name: formatUserName(user) }; return saveUserToDatabase(formattedUser); } // Each function has single responsibility

✓ Benefits: Single responsibility, Easy to test, Reusable

3. Early Returns Returns

// Compliant: Early returns reduce nesting function processOrder(order) { if (!order) return null; if (!order.items || order.items.length === 0) return null; return order.items .filter(item => item.price > 0 && item.stock > 0) .map(item => processItem(item)); } // Flat structure, easy to read

✓ Benefits: Reduced nesting, Clearer logic

4. DRY Principle DRY

// Compliant: DRY - Don't Repeat Yourself function validateRequired(value, minLength = 0) { if (!value) return false; if (value.length < minLength) return false; return true; } function validateEmail(email) { if (!validateRequired(email, 5)) return false; return email.includes('@'); } function validateUsername(username) { return validateRequired(username, 3); } function validatePassword(password) { return validateRequired(password, 8); } // Reusable validation function

✓ Benefits: Single source of truth, Easy to maintain

5. Descriptive Variable Names Naming

// Compliant: Descriptive names const userData = getUserData(); const processedData = processUserData(userData); const formattedData = formatUserData(processedData); const result = saveUserData(formattedData); function calculateTotalPrice(basePrice, taxRate, discount) { const taxAmount = basePrice * taxRate; const discountedPrice = basePrice - discount; return discountedPrice + taxAmount; } const currentDate = new Date(); const timestamp = currentDate.getTime(); // Names explain purpose

✓ Benefits: Self-documenting, Easy to understand

6. Clean Codebase Clean

// Compliant: No dead code function calculateTotal(items) { return items.reduce((sum, item) => sum + item.price * 1.1, 0); } // TODO: Add discount logic when requirements are finalized // function applyDiscount(total, user) { // if (user.hasDiscount) { // return total * 0.9; // } // return total; // } // Only active code, TODOs tracked in issue tracker

✓ Benefits: Clean codebase, No confusion

7. Single Responsibility Principle SRP

// Compliant: Single responsibility class UserRepository { create(user) { } update(id, user) { } delete(id) { } findById(id) { } } class EmailService { send(to, subject, body) { } } class PaymentProcessor { process(payment) { } } // Each class has one reason to change

✓ Benefits: Focused classes, Easy to test

8. Consistent Code Style Style

// Compliant: Consistent style (using ESLint/Prettier) async function getUserData() { return await fetch('/api/user'); } async function getOrderData() { return await fetch('/api/order'); } async function getProductData() { return await fetch('/api/product'); } // Consistent patterns, formatting, and conventions

✓ Benefits: Consistent, Readable, Maintainable

9. Comprehensive Error Handling Errors

// Compliant: Error handling async function loadUserData(userId) { try { if (!userId) { throw new Error('User ID is required'); } const user = await database.getUser(userId); if (!user) { throw new Error(`User ${userId} not found`); } const orders = await database.getOrders(userId); const preferences = await database.getPreferences(userId); return { user, orders, preferences }; } catch (error) { logger.error('Failed to load user data', { userId, error }); throw error; } } // Validates input, handles errors, logs issues

✓ Benefits: Robust, Debuggable, User-friendly

10. Configuration Management Config

// Compliant: Configuration management // config/database.js module.exports = { host: process.env.DB_HOST || 'localhost', port: process.env.DB_PORT || 5432, username: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME }; // config/api.js module.exports = { apiUrl: process.env.API_URL || 'https://api.example.com/v1', maxRetries: parseInt(process.env.MAX_RETRIES || '3'), timeout: parseInt(process.env.TIMEOUT || '5000') }; // Values in config files, environment variables

✓ Benefits: Environment-specific, Secure, Flexible

11. Encapsulated State State

// Compliant: Encapsulated state class UserStore { constructor() { this.currentUser = null; this.isLoggedIn = false; this.cartItems = []; } setUser(user) { this.currentUser = user; this.isLoggedIn = !!user; } addToCart(item) { this.cartItems.push(item); this.notifySubscribers(); } notifySubscribers() { // Notify UI of changes } } // State encapsulated in class, controlled access

✓ Benefits: Controlled access, Testable, Maintainable

12. Parameter Objects Parameters

// Compliant: Parameter objects function createUser(userData) { const { firstName, lastName, email, phone, address, city, state, zip, country, birthDate, gender, role, department, salary, startDate, manager, notes } = userData; return { firstName, lastName, email, phone, address, city, state, zip, country, birthDate, gender, role, department, salary, startDate, manager, notes }; } createUser({ firstName: 'John', lastName: 'Doe', email: 'john@example.com' // ... other fields }); // Easy to call, clear parameter names

✓ Benefits: Clear parameters, Easy to use, Flexible

13. Type Checking Types

// Compliant: Type checking function calculateTotal(items) { if (!Array.isArray(items)) { throw new TypeError('Items must be an array'); } return items.reduce((sum, item) => { if (typeof item.price !== 'number') { throw new TypeError('Item price must be a number'); } return sum + item.price; }, 0); } // Or use TypeScript function calculateTotal(items: Array<{ price: number }>): number { return items.reduce((sum, item) => sum + item.price, 0); } // Type validation prevents runtime errors

✓ Benefits: Type safety, Early error detection

14. Dependency Injection DI

// Compliant: Dependency injection class OrderService { constructor(database, emailService, paymentProcessor, cache) { this.database = database; this.emailService = emailService; this.paymentProcessor = paymentProcessor; this.cache = cache; } async processOrder(order) { await this.database.save(order); await this.emailService.send(order.user.email, 'Order confirmed'); await this.paymentProcessor.charge(order.total); await this.cache.set(`order:${order.id}`, order); } } // Dependencies injected - easy to test and swap

✓ Benefits: Loose coupling, Testable, Flexible

15. Comprehensive Documentation Docs

/** * Calculates the total price including tax for eligible items. * * @param {Array} items - Array of items with price and status * @param {number} items[].price - Item price * @param {number} items[].status - Item status (1 = eligible for tax) * @returns {Array} Array of processed items with tax and total * * @example * const items = [ * { id: 1, price: 100, status: 1 }, * { id: 2, price: 50, status: 0 } * ]; * const result = calculateTotalWithTax(items); * // Returns: [{ id: 1, price: 100, tax: 15, total: 115 }] */ function calculateTotalWithTax(items) { const TAX_RATE = 0.15; const MINIMUM_PRICE = 100; const ELIGIBLE_STATUS = 1; return items .filter(item => item.status === ELIGIBLE_STATUS && item.price > MINIMUM_PRICE) .map(item => ({ id: item.id, tax: item.price * TAX_RATE, total: item.price + (item.price * TAX_RATE) })); } // Well-documented with JSDoc, clear examples

✓ Benefits: Self-documenting, IDE support, Maintainable

16. Code Quality Tools Tools

// Compliant: Using code quality tools // .eslintrc.js module.exports = { extends: ['eslint:recommended', 'plugin:react/recommended'], rules: { 'no-console': 'warn', 'no-unused-vars': 'error', 'complexity': ['error', 10], 'max-lines': ['warn', 500] } }; // .prettierrc { "semi": true, "singleQuote": true, "tabWidth": 2 } // package.json { "scripts": { "lint": "eslint .", "format": "prettier --write .", "test": "jest", "coverage": "jest --coverage" } } // Automated code quality checks

✓ Benefits: Automated checks, Consistent style, Early detection

About This Page

This page is designed for:

  • Testing code quality analysis tools
  • Training developers on code quality best practices
  • Understanding code smells and technical debt
  • Learning about maintainability and readability

Remember: Write clean, maintainable code. Use meaningful names, keep functions small and focused, follow DRY principles, handle errors properly, and use code quality tools like ESLint, Prettier, and TypeScript. Code is read more often than it's written.