Discuss a project

Blog / Management

Code quality: from a personal practice to a team culture

Introduction

In modern software development, code is not just a means of reaching functional goals. It is a living, constantly evolving asset that will shape the future of the product for years to come. Responsibility for code quality does not start with one particular officer or role; it is the foundation of every developer's professional culture. In this article we look at why every developer should take responsibility for code quality, how this affects the productivity of the whole team, and how to build a culture of high-quality programming.

Why code quality is everyone's responsibility

Many developers are used to thinking that code quality is the job of testers, architects or managers. This is a fundamental misconception that can cost a company enormous resources. Code quality starts with the first commit and continues throughout the entire life cycle of the project.

Unity of responsibility

Imagine a car assembly process in which only individual engineers are responsible for the quality of particular parts, but nobody is responsible for the overall integrity and reliability of the design. That is unthinkable in real manufacturing, and software development is no different. Every piece of code a developer writes becomes part of a shared system that will be operated by other people.

When responsibility for code quality is delegated, diffusion of responsibility appears: every developer assumes that others will answer for their shortcomings, and stops feeling personally involved in the result. As a result nobody owns the product, which leads to a gradual degradation of the codebase.

Quality as an investment, not an expense

It is hard to overstate the importance of code quality in terms of ROI (return on investment). High-quality code makes it possible to:

  • Cut the time spent on developing new features by 30-50%
  • Reduce the number of regression bugs by 60-80%
  • Increase deployment frequency by 2-3 times
  • Reduce the cost of maintenance and refactoring

Every hour spent on writing high-quality code, with documentation, tests and a clean architecture, saves dozens of hours in the future. That is the difference between an investment and an expense.

Architectural principles for maintainable code

High-quality code starts with the right architecture. There is no single correct approach, but there are fundamental principles that help to create maintainable code.

SOLID principles

SOLID is a set of object-oriented programming principles that serve as a guide for building flexible and extensible systems.

Single Responsibility Principle (SRP):

"A class should have only one reason to change."

This means that a class should have one clearly defined responsibility. For example, a `UserRepository` class should be responsible only for saving and retrieving users, not for managing access rights.

Example of a bad implementation:

class UserService {
  // Too many responsibilities
  saveUser(user: User): void { ... }
  authorize(user: User, resource: string): boolean { ... }
  sendWelcomeEmail(user: User): void { ... }
  generateReports(): Report { ... }
}

A good implementation:

class UserService {
  saveUser(user: User): void { ... }

  constructor(
    private repo: UserRepository,
    private auth: AuthService,
    private emailService: EmailService
  ) {}
}

class AuthService {
  // Authorization only
  authorize(user: User, resource: string): boolean { ... }
}

Open/Closed Principle (OCP):

"Software entities should be open for extension, but closed for modification."

This means that we should design the system so that new functionality is added through extension rather than through modification of existing code.

Example using the strategy pattern:

interface PaymentStrategy {
  pay(amount: number): void;
}

class StripePayment implements PaymentStrategy {
  pay(amount: number): void {
    // Stripe payment logic
  }
}

class PayPalPayment implements PaymentStrategy {
  pay(amount: number): void {
    // PayPal payment logic
  }
}

class OrderProcessor {
  constructor(private strategy: PaymentStrategy) {}

  process(amount: number): void {
    this.strategy.pay(amount);
  }
}

// A new strategy is added without modifying OrderProcessor
class CryptoPayment implements PaymentStrategy {
  pay(amount: number): void {
    // Crypto payment logic
  }
}

Liskov Substitution Principle (LSP):

"Subclasses should be interchangeable with their base classes."

This is a critically important principle that prevents problems with inheritance. It is important that subclasses do not break the expected behavior of the base class.

Interface Segregation Principle (ISP):

"Clients should not depend on interfaces they do not use."

Avoid creating bulky interfaces with many methods. It is better to have several narrow, specialized interfaces.

Dependency Inversion Principle (DIP):

"High-level modules should not depend on low-level modules. Both should depend on abstractions."

Applying this principle lets you swap implementations at the configuration level without changing high-level code.

Clean architecture

Clean Architecture is a hierarchy of dependencies that allows developers to change implementation details without affecting the business logic.

┌─────────────────────────────────┐
│   External elements (In/Out)    │
├─────────────────────────────────┤
│   Frameworks & Drivers          │
├─────────────────────────────────┤
│   Interface Adapters            │
├─────────────────────────────────┤
│   Use Cases                     │
├─────────────────────────────────┤
│   Entities & Domain Logic       │
└─────────────────────────────────┘

Key advantages:

  • Dependencies flow inward: All dependencies point toward the center of the architecture
  • Testing: You can test business logic without frameworks and external dependencies
  • Flexibility: You can change the technology stack without changing the business logic

DRY and KISS

Don't Repeat Yourself (DRY):

Every time you see duplicated code, it is a signal that you are missing an abstraction. Duplication leads to bugs, because changes have to be applied in several places.

Example of duplication:

// Duplicated validation
function createUser(data: UserData): User {
  if (!data.email) throw new Error('Email is required');
  if (!data.password) throw new Error('Password is required');

  // ... create the user
}

function updateProfile(data: ProfileData): Profile {
  if (!data.email) throw new Error('Email is required');
  if (!data.name) throw new Error('Name is required');

  // ... update the profile
}

The fix with DRY:

class Validator {
  static validate(data: any, schema: Schema): ValidationResult {
    // Shared validation logic
  }
}

function createUser(data: UserData): User {
  const validation = Validator.validate(data, userSchema);
  if (!validation.isValid) throw new Error('Invalid data');

  // ... create the user
}

Keep It Simple, Stupid (KISS):

Complexity is the enemy of reliability and maintainability. Avoid architectural excess where a simple solution is enough.

Example of overcomplicated code:

// Too complex
class ComplexService {
  async process(data: any): Promise {
    try {
      const validation = await this.validationService.validate(data);
      if (!validation.valid) return Result.fail(validation.errors);

      const transformation = await this.transformationService.transform(data);
      const processing = await this.processingService.process(transformation);
      const enrichment = await this.enrichmentService.enrich(processing);

      return Result.success(enrichment);
    } catch (error) {
      return Result.fail(['An error occurred']);
    }
  }
}

A simple solution:

// Simpler
class SimpleService {
  async process(data: any): Promise {
    if (!this.isValid(data)) return Result.fail(['Invalid data']);

    return Result.success(this.transform(data));
  }

  private isValid(data: any): boolean {
    return data !== null && data !== undefined;
  }

  private transform(data: any): any {
    return { ...data, processedAt: new Date().toISOString() };
  }
}

Testing: the foundation of reliability

Without tests, code becomes fragile. Tests not only catch errors, they also serve as documentation that shows how the code works.

Types of tests

Unit tests:

They test individual functions or methods in isolation. This is the fastest type of test, and it gives instant feedback.

describe('AuthService', () => {
  it('should authenticate user with valid credentials', () => {
    const auth = new AuthService(new MockUserRepository());
    const result = auth.login('user@example.com', 'password');

    expect(result.success).toBe(true);
    expect(result.token).toBeDefined();
  });
});

Integration tests:

They test the interaction between components or systems. They make sure the components work together correctly.

describe('UserRegistration', () => {
  it('should register user and send welcome email', async () => {
    const mockEmailService = new MockEmailService();
    const registration = new UserRegistration(
      new MockUserRepository(),
      mockEmailService
    );

    const result = await registration.register({
      email: 'user@example.com',
      password: 'password123'
    });

    expect(result.success).toBe(true);
    expect(mockEmailService.sentEmails).toHaveLength(1);
  });
});

E2E tests:

They test a complete user scenario from start to finish. They show how the system works from the user's point of view.

describe('User Journey', () => {
  it('should allow user to register and login', async () => {
    // Registration
    await page.goto('http://localhost:3000/register');
    await page.fill('input[name="email"]', 'user@example.com');
    await page.fill('input[name="password"]', 'password123');
    await page.click('button[type="submit"]');

    // Check that registration succeeded
    await expect(page.locator('.welcome-message')).toBeVisible();

    // Login
    await page.goto('http://localhost:3000/login');
    await page.fill('input[name="email"]', 'user@example.com');
    await page.fill('input[name="password"]', 'password123');
    await page.click('button[type="submit"]');

    // Check that login succeeded
    await expect(page.locator('.dashboard')).toBeVisible();
  });
});

Code coverage tests:

They measure what percentage of the code is covered by tests. The goal is 80% or higher for critical code paths.

// jest.config.js
module.exports = {
  collectCoverageFrom: [
    'src/**/*.{js,ts}',
    '!src/**/*.d.ts',
    '!src/**/*.test.{js,ts}',
    '!src/**/index.ts'
  ],
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80
    }
  }
};

Testing side effects

Not every function has a clear return value, so it is important to check side effects.

describe('EmailService', () => {
  it('should send email with correct content', async () => {
    const mockMailer = new MockMailer();
    const emailService = new EmailService(mockMailer);

    await emailService.sendWelcomeEmail('user@example.com', 'John');

    expect(mockMailer.sent).toHaveBeenCalledWith({
      to: 'user@example.com',
      subject: 'Welcome!',
      body: expect.stringContaining('John')
    });
  });
});

Test isolation

Every test must be independent and isolated. There should be no dependencies between tests.

describe('UserService', () => {
  let mockUserRepository: MockUserRepository;
  let mockAuthService: AuthService;

  // Hook for setup before each test
  beforeEach(() => {
    // Create a clean state
    mockUserRepository = new MockUserRepository();
    mockAuthService = new AuthService(mockUserRepository);
  });

  // Each test runs in isolation
  it('should create user', () => {
    // ... test
  });

  it('should update user', () => {
    // ... test
  });
});

Refactoring as part of the process

Refactoring is the process of improving the structure of code without changing its external behavior. It is a key element of a maintainable codebase.

When to refactor

Daily refactoring:

Small improvements made while you work:

// Code style improvement
// Before
function process(data: Data): Result {
  const result = data.process();
  return result;
}

// After
function process(data: Data): Result {
  return data.process();
}

// Field encapsulation
// Before
class User {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}

// After
class User {
  constructor(private _name: string) {}

  get name(): string { return this._name; }
}

Technical debt:

Regular work on accumulated debt:

// Weekly code audit
1. Identify problems: duplication, complex functions, weak typing
2. Prioritize: criticality, impact on the system, difficulty of the fix
3. Plan: distribute the tasks across sprints

// Example of refactoring duplication
function sendEmail(to: string, subject: string, body: string) {
  // Duplicated validation logic
  if (!to || !subject) throw new Error('Missing required fields');

  // Send via SMTP
  smtpClient.send(to, subject, body);
}

function sendNotification(to: string, message: string) {
  // The same validation
  if (!to || !message) throw new Error('Missing required fields');

  // Send via push notifications
  pushClient.send(to, message);
}

High-priority situations:

When old code gets in the way of new functionality:

// Situation: a new feature cannot be added because of the old code
// Before
class OrderProcessor {
  process(order: Order): void {
    // Legacy logic
    const subtotal = this.calculateSubtotal(order);
    const discount = this.calculateDiscount(subtotal);
    const tax = this.calculateTax(subtotal);

    // There is nowhere to put the new feature (loyalty bonus)
    // without breaking the existing calculations
  }
}

// After: the price calculation is moved into a separate class
class PricingCalculator {
  constructor(
    private discountService: DiscountService,
    private taxService: TaxService,
    private loyaltyService: LoyaltyService
  ) {}

  calculateTotal(order: Order): number {
    // All calculation steps, including the new loyalty bonus
  }
}

class OrderProcessor {
  constructor(private pricing: PricingCalculator) {}

  process(order: Order): void {
    const total = this.pricing.calculateTotal(order);
  }
}

Refactoring techniques

Rename refactoring:

Changing the names of variables, functions and classes for better readability.

// Before
function calcAge(dob: Date): number {
  const today = new Date();
  return today.getFullYear() - dob.getFullYear();
}

// After
function calculateAge(dateOfBirth: Date): number {
  const today = new Date();
  return today.getFullYear() - dateOfBirth.getFullYear();
}

Extract Method:

Moving logic into a separate function.

// Before
function processOrder(order: Order): void {
  const subtotal = calculateSubtotal(order.items);
  const discount = applyDiscount(subtotal);
  const tax = calculateTax(subtotal);
  const total = subtotal - discount + tax;

  chargeCard(total, order.paymentMethod);
  sendConfirmationEmail(order.email, order.id);
}

// After
function processOrder(order: Order): void {
  const total = calculateOrderTotal(order);

  chargeCard(total, order.paymentMethod);
  sendConfirmationEmail(order.email, order.id);
}

function calculateOrderTotal(order: Order): number {
  const subtotal = calculateSubtotal(order.items);
  const discount = applyDiscount(subtotal);
  const tax = calculateTax(subtotal);

  return subtotal - discount + tax;
}

Extract Class:

Moving behavior into a separate class.

// Before
class Invoice {
  number: string;
  date: Date;
  items: InvoiceItem[];
  total: number;

  generate(): string {
    // Complex PDF generation
    const header = this.generateHeader();
    const itemsSection = this.generateItemsSection();
    const footer = this.generateFooter();

    return `${header}\n${itemsSection}\n${footer}`;
  }
}

// After
class Invoice {
  constructor(
    private generator: InvoiceGenerator,
    private formatter: InvoiceFormatter
  ) {}

  generate(): string {
    const header = this.generator.generateHeader(this);
    const itemsSection = this.generator.generateItemsSection(this);
    const footer = this.generator.generateFooter(this);

    return this.formatter.format([header, itemsSection, footer]);
  }
}

class InvoiceGenerator {
  generateHeader(invoice: Invoice): string { /* ... */ }
  generateItemsSection(invoice: Invoice): string { /* ... */ }
  generateFooter(invoice: Invoice): string { /* ... */ }
}

class InvoiceFormatter {
  format(content: string[]): string { /* ... */ }
}

A culture of quality code in the team

High-quality code is not only a technical problem but a cultural one. Building a culture of high-quality programming takes effort from every member of the team. We write about how code quality relates to motivation in the article Developer Motivation: Clean Code and Architecture.

Setting expectations and standards

Code review as a norm:

Code review is not a check for errors but an exchange of knowledge and joint development.

# Code Review rules

1. Show respect and support your colleagues
2. Be constructive and specific
3. Comment on the code first, not on the developer as a person
4. Describe alternative solutions
5. Keep a balance between speed and quality

# What to look for in a review

- Compliance with code standards
- Readability and maintainability
- Testing
- Edge cases
- Performance implications

A checklist for the developer before a PR:

- ✅ The logic is covered by tests (unit and integration)
- ✅ The code meets the standards
- ✅ All tests pass
- ✅ The code is documented (comments, JSDoc)
- ✅ Refactoring is done where possible
- ✅ No new technical debt is added
- ✅ It can be run and verified

Tooling for quality

Linter and Formatter:

Built-in code quality checks.

// .eslintrc.js
module.exports = {
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'prettier'
  ],
  rules: {
    '@typescript-eslint/no-explicit-any': 'error',
    'no-console': ['warn', { allow: ['warn', 'error'] }],
    'prefer-const': 'error'
  }
};

// package.json scripts
{
  "scripts": {
    "lint": "eslint src --ext .ts,.tsx",
    "lint:fix": "eslint src --ext .ts,.tsx --fix",
    "format": "prettier --write src/**/*.{ts,tsx,json,md}"
  }
}

Static Analysis:

Analyzing code at an early stage to detect problems.

// tsconfig.json
{
  "compilerOptions": {
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "skipLibCheck": true
  }
}

Automated Tests:

Automatic testing on every commit and pull request.

// .github/workflows/ci.yml
name: CI

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
        with:
          node-version: '18'

      - name: Install dependencies
        run: npm ci

      - name: Run linter
        run: npm run lint

      - name: Run tests
        run: npm test -- --coverage

      - name: Upload coverage
        uses: codecov/codecov-action@v2

Learning and development

On how to build the growth of beginner developers in such an environment, see the article Best Experience for a Junior Developer.

Tech Talks:

Weekly talks for sharing knowledge.

# Example of a talk topic

## "React Hooks anti-patterns and how to avoid them"
- Why Hooks can be problematic
- Common pitfalls: dependency arrays, stale closures
- Best practices: custom hooks, dependency extraction
- Examples of real code with mistakes and fixes

## "Test-Driven Development: Myth or Reality?"
- TDD basics: Red-Green-Refactor
- When to apply TDD
- How many tests are enough
- Practical examples

Code Reviews as learning:

Gradually developing skills through discussing code.

# Constructive feedback format

When I see a complex piece of code:
1. I ask: "Why is it implemented this way here?"
2. We discuss alternatives
3. If there are options, we propose a refactoring
4. I present it as an opportunity for learning

Example:
❌ "This code is complex, rewrite it"
✅ "I see complex logic here. I wonder what solution you used?
   Are there simpler alternatives? I see the strategy pattern might help"

Balance between speed and quality

Reasonable compromises:

You do not need to be a perfectionist. Some aspects can be imperative.

# Important vs Urgent

| Quality                | When it is the priority      |
|------------------------|------------------------------|
| Full test coverage     | Business-critical features   |
| Perfect architecture   | MVP and scalability          |
| Code style             | A long-term project          |
| Avoiding all risks     | Fast adaptation to the market|

| Speed                  | When it is the priority      |
|------------------------|------------------------------|
| MVP features           | New features in the MVP      |
| Fast deploy            | Demonstrating value          |
| Minimum viable tests   | Small features               |
| Refactoring as you grow| Code base > 10k LOC          |

Good enough code:

Accepting that "good enough" is fine.

// Bad goal: perfect, but never
function calculateExactTax(amount: number, rate: number): number {
  // A tricky calculation accurate to the cent
  // It will never be finished
  throw new Error('Calculation is not implemented');
}

// Good goal: sufficient, but still reliable
function calculateTax(amount: number, rate: number): number {
  // A calculation with sufficient precision
  // Correct rounding
  // Compliance with tax law
  return Math.round(amount * rate * 100) / 100;
}

Measuring code quality

To manage quality, you need to measure it. This lets you spot trends, prioritize effort and evaluate the effectiveness of changes.

Quality metrics

Test coverage:

// Local check
npm test -- --coverage

// Average coverage across the project
{
  "total": 78,
  "lines": 82,
  "functions": 71,
  "branches": 70,
  "statements": 80
}

Targets:

  • Business-critical functions: 90%+
  • Core logic: 80%+
  • Utility code: 60-70%

Code complexity:

// Using eslint-plugin-complexity
{
  "complexity": {
    "max-classes-per-file": 5,
    "max-depth": 4,
    "max-lines-of-code": 500,
    "max-nested-callbacks": 4,
    "max-params": 5
  }
}

Number and quality of PRs:

# Team metrics

✅ PRs submitted: 3 per sprint
✅ Average PR size: 200 LOC
✅ Avg. time in review: 2 days
✅ Avg. time to approval: 1 day
✅ Auto-merge applied: 80%

Bottlenecks:

Identifying and prioritizing problem areas.

// Logging bottlenecks
const performanceMetrics = {
  functions: [
    { name: 'calculateComplexFormula', complexity: 12, calls: 1000 },
    { name: 'processBatch', complexity: 8, calls: 500 },
    { name: 'simpleValidation', complexity: 2, calls: 10000 }
  ],

  // Top 3 problems
  problems: [
    { name: 'calculateComplexFormula', issue: 'High complexity' },
    { name: 'processBatch', issue: 'Too many dependencies' },
    { name: 'executeDatabaseQuery', issue: 'N+1 query problem' }
  ]
};

Conclusion

Responsibility for code quality is not a job duty but a fundamental part of a developer's professional identity. High-quality code is not a luxury but a necessary asset for the successful growth of a project and an organization.

Key points:

  1. Unity of responsibility: Code quality is the job of every developer
  2. Architectural principles: SOLID, clean architecture, DRY, KISS
  3. Testing: the foundation of reliability and documentation
  4. Refactoring: a process of continuous improvement
  5. Culture: building a team that values quality
  6. Measurement: objective assessment and improving trends

Building a culture of quality code takes time, but the investment pays off many times over. High-quality code allows a team to:

  • Ship new features faster
  • Spend less time fixing bugs
  • Onboard new team members faster
  • Lower the cost of maintenance
  • Increase confidence in the product

Remember: the code you write today will be read by your colleagues tomorrow, and it will be maintained by other people. Invest in quality today, and you will save the time of everyone on the project in the future.

Shall we discuss your project?

Tell us about your task and we will come back with an estimate of the time and the cost within two working days.