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: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:
// 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: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: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.