Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 50 ยท Quality, Testing and Delivery

TDD and Code Quality Practices

Learn the red-green-refactor cycle of test-driven development, what static analysis finds, how cyclomatic complexity is counted, and why code coverage can mislead.

Testing after the fact tells you whether the code you wrote happens to work. Test-driven development (TDD) flips the order: you write a failing test first, then just enough code to make it pass. Alongside that habit, teams use tools that read the code without running it (static analysis) and numbers that describe it (metrics). Together they aim at one thing: code that is correct today and still safe to change next year.

TDD itself needs only a test framework and an editor, and the quality tools (linters, SonarQube-style dashboards, coverage reporters) are products you install in a real project. None of them can run on this site. Every example below is therefore a plain JavaScript stand-in: a tiny test runner, a tiny complexity counter, and a tiny coverage tracker, written so you can see how the idea works inside. Real tools do the same jobs with far more care. For testing basics see testing levels and strategy and test design techniques.

Red, green, refactor

TDD is a loop with three short steps, repeated every few minutes:

  1. Red. Write one small test for behavior that does not exist yet. Run it and watch it fail. The failure proves the test can fail, which means a later pass is meaningful.
  2. Green. Write the simplest code that makes the test pass. It may be ugly or even hard-coded. The goal is only to get back to a passing suite.
  3. Refactor. With all tests green, clean up the code (names, duplication, structure) without changing behavior. The tests are your safety net: if one turns red, you broke something and can undo the last step.
flowchart LR
    R["Red<br/>write a failing test"] --> G["Green<br/>make it pass, simply"]
    G --> F["Refactor<br/>clean up, tests stay green"]
    F --> R

The TDD loop. One lap should take minutes, not hours.

The TDD loop

Red One failing test first.
Green Simplest code that passes.
Refactor Clean up, stay green.

Small steps keep every failure easy to explain.

1 / 2

The third benefit deserves a moment. If a function is painful to test because it reads the clock, talks to a database and prints to the screen all at once, the pain is a design signal. TDD makes you feel it before the code is written, when changing the design is cheap (compare design principles).

A TDD session in miniature

Suppose a requirement says: "A password is acceptable when it has at least 8 characters and at least one digit." Instead of writing the function, we write the first test and a minimal runner. The function does not exist yet, so the first run is deliberately red.

JS Red: the test fails first

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Now the green step. We add code that passes, and then add more tests that force the rest of the requirement to appear, one rule at a time. The second test is red against the first implementation, which is exactly the point: each test earns its code.

JS Green and refactor with more tests

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real projects use a framework (JUnit, pytest, Jest and many others) instead of a hand-written test function, but the loop is the same. TDD does not guarantee good design on its own, and it is not required everywhere: throwaway scripts and exploratory UI work are often better served by testing afterward. Its sweet spot is logic with clear rules, such as pricing, validation and parsing.

Write the test name as a sentence describing behavior ("rejects a password that is too short"). When a test fails in the pipeline months later, the name is the first thing a stranger reads.

Static analysis: reading code without running it

Static analysis inspects source code (or compiled code) without executing it. It finds problems that tests might never trigger:

  • Style and formatting issues (a linter or formatter handles these, so humans stop arguing about them in reviews).
  • Likely bugs: unused variables, unreachable code, comparing values that can never be equal, using a variable that may be null.
  • Type errors, found by a compiler or type checker before the program runs.
  • Security patterns: building SQL from user input, hard-coded secrets, weak cryptographic functions.
  • Duplication and complexity that make code hard to maintain.

Static analysis is cheap and fast, so it usually runs in the editor and again in the delivery pipeline as a gate. It has two limits. It produces false positives (warnings about code that is actually fine), which teams must tune or suppress with a written reason. And it cannot know what the program is supposed to do, so it never replaces tests. The CI/CD track shows how to wire such checks as quality gates.

Metrics: numbers about code

Metrics turn code into numbers so that trends become visible. Common ones are lines of code, duplication percentage, size of functions and classes, number of dependencies between modules, and the two below. Use them to start conversations, never as targets. When a number becomes a goal, people optimize the number rather than the code.

Cyclomatic complexity

Cyclomatic complexity, introduced by Thomas McCabe, counts the independent paths through a piece of code. A simple way to compute it for one function is:

TEXT
complexity = number of decision points + 1

Decision points are the places where the flow can split: if, loops, case branches, catch, and each && or || (because those short-circuit). A function with no branches has complexity 1. Each extra decision adds one path that a thorough test suite must cover, so the number also tells you the minimum count of tests needed to exercise every branch.

Rough guidance used in many teams: 1 to 10 is simple, 11 to 20 is getting hard to test, and above that the function should usually be split. These thresholds are conventions, not laws.

The stand-in below counts decision keywords in a source string. A real tool parses the code into a syntax tree and ignores keywords inside strings and comments, which this simple version does not, so treat it as an illustration of the formula.

JS A tiny complexity counter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

When a function scores high, the usual cure is extracting well-named helper functions, which is the refactoring step of TDD again (see technical debt and refactoring).

Code coverage and its limits

Code coverage measures how much of the code the tests executed. Line coverage counts lines run; branch coverage counts whether both outcomes of each decision were taken, which is stricter. Coverage tools are real products (usually built into the test framework or a separate reporter) and they are good at one thing: showing code that no test touched at all. An untested branch is a certain blind spot.

What coverage cannot do is prove the tests are good. A line counts as covered when it runs, even if no assertion checks the result. A test with no assertions can give 100% coverage and catch nothing. The next stand-in shows the trap with a deliberately buggy discount function and a weak test.

JS 100% coverage, bug still there

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Use coverage as a floor and a map, not a trophy. A reasonable policy is "new code must not lower coverage and every important branch has a test with a real assertion". Chasing 100% tends to produce tests that exist only for the number. Some teams also use mutation testing, which deliberately introduces small bugs (flipping > to >=) and checks whether any test fails. It measures test strength, not just reach, at a high cost in run time.

Putting the practices together

None of these tools stands alone. A healthy loop looks like this: TDD gives you tests as a by-product, the linter and type checker catch cheap mistakes while you type, the pipeline runs everything on every change, coverage shows the untested corners, and complexity trends tell you where the next refactoring should go. Humans still do code review on top, because tools cannot judge whether a design is clear.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does TDD ask you to see the new test fail before writing the code?

    A test that has never failed might be unable to fail. Seeing it red first shows it checks real behavior.
  2. 2. A function has two if statements, one loop and one && in a condition. What is its cyclomatic complexity?

    Decision points are 2 + 1 + 1 = 4, and complexity is decision points + 1 = 5.
  3. 3. Which statement about code coverage is true?

    A line is covered when it runs. Untested code is visible, but weak tests can still reach every line.
  4. 4. What can static analysis NOT do on its own?

    Static tools inspect code structure and patterns. They have no knowledge of the intended behavior, so tests and reviews are still needed.
  5. 5. In the refactor step of red-green-refactor, what must be true?

    Refactoring changes structure, not behavior, and the passing tests are how you know that.

Summary

  • TDD is the loop red (failing test), green (simplest passing code), refactor (clean up while tests stay green).
  • Static analysis reads code without running it: linters, type checkers and security scanners catch cheap mistakes but cannot judge intent.
  • Cyclomatic complexity is decision points plus one; high values mark code that is hard to test and understand.
  • Coverage reveals untested code but cannot prove tests are strong; mutation testing probes test strength.
  • Treat metrics as conversation starters, not targets.

Next: Version Control, CI and Delivery Pipelines.