Knowledge / Computer Science and Engineering / Clean code and code reviews

Clean code and code reviews

Computer Science and Engineering (B.E./B.Tech) · Software engineering · free study notes for exams, placements and interviews

In short

Clean code is source code that is readable, small-stepped, consistently named, easy to change and easy to test; a code review is the human (and tool-assisted) static examination of that code before it is merged. Both exist because software is read far more often than it is written, and because a defect caught in review costs a fraction of the same defect caught in production. University syllabi examine this as *coding standards, program comprehension, walkthroughs, inspections, software metrics and refactoring* under Software Engineering, and GATE-style questions ask for cyclomatic complexity, review types and quality metrics. Every Indian employer with a merge process - TCS, Infosys, Wipro, Cognizant, Zoho, Flipkart, Swiggy, Qualcomm, Samsung R&D, Bosch, Tata Elxsi - gates code on review plus a static-analysis quality gate, and "walk me through how you review a pull request" is now a standard interview question for freshers.

Explained

What "clean code" means

The clean-code rules: names, functions, comments, formatting, errors

Code smells, refactoring and the design principles behind them

Measuring code quality: metrics, static analysis, technical debt

Code reviews: types under IEEE 1028 and the review process

Modern pull-request review in practice

Standards, compliance and Indian industry practice

Key points

Formulas and examples

V(G) = E − N + 2P = (number of binary decision predicates) + 1
E = edges, N = nodes of the control-flow graph, P = connected components (P = 1 for a single function)
Defect density = total defects ÷ size in KLOC (defects per 1,000 lines of code)
Defect Removal Efficiency DRE = D_before ÷ (D_before + D_after) × 100 %
D_before = defects found before release, D_after = defects found by users after release
Review rate = LOC reviewed ÷ reviewer-hours (guideline 150-300 LOC/hour)
Review ROI = (defects caught in review × cost avoided per defect) ÷ (review effort × loaded cost per hour)
Maintainability Index MI = 171 − 5.2 ln(V) − 0.23 G − 16.2 ln(LOC); normalised MI = max(0, MI × 100 ÷ 171)
V = Halstead volume (bits), G = cyclomatic complexity, LOC = lines of code
Technical Debt Ratio TDR = remediation cost ÷ cost to develop the same code × 100 %
Comment density = comment lines ÷ total lines; Instability I = Ce ÷ (Ca + Ce) for a module

Example 1 - cyclomatic complexity of a function, both ways

def grade(marks, attendance):
    if marks is None:              # d1
        return "INVALID"
    if attendance < 75:            # d2
        return "DETAINED"
    if marks >= 90:                # d3
        return "A"
    elif marks >= 75:              # d4
        return "B"
    elif marks >= 40:              # d5
        return "C"
    else:
        return "F"

Example 2 - refactoring the same function and re-measuring

BANDS = ((90, "A"), (75, "B"), (40, "C"))      # cut-offs are now data

def grade(marks, attendance):
    if marks is None:
        return "INVALID"
    if attendance < 75:
        return "DETAINED"
    return band_for(marks)

def band_for(marks):
    for cutoff, band in BANDS:
        if marks >= cutoff:
            return band
    return "F"

Example 3 - review effort, yield and rupee ROI A release changes 9,000 LOC. House norm: 2 reviewers per change, effective review rate 200 LOC/hour, loaded engineer cost ₹900/hour. Pre-review defect density 12 defects/KLOC; review DRE 55%. Fixing a defect in review ≈ ₹1,500; the same defect escaping to production ≈ ₹30,000.

  1. Reviewer-hours per reviewer = 9,000 ÷ 200 = 45 h; two reviewers → 90 person-hours.
  2. Review cost = 90 × ₹900 = ₹81,000.
  3. Latent defects = 9 KLOC × 12 = 108; caught in review = 108 × 0.55 = 59 (rounded).
  4. Cost avoided per defect = ₹30,000 − ₹1,500 = ₹28,500 → total avoided = 59 × 28,500 = ₹16,81,500.
  5. Net benefit = ₹16,81,500 − ₹81,000 = ₹16,00,500; ROI ≈ 16,81,500 ÷ 81,000 ≈ 20.8×.
  6. Sessions needed = 9,000 ÷ 300 LOC per sitting = 30 sittings, so this must be spread across the sprint, not done the night before release.

Example 4 - Defect Removal Efficiency and release quality A 45 KLOC product: reviews found 110 defects, testing found 70, and users reported 20 in the first three months.

Example 5 - Maintainability Index before and after extraction A payment handler: LOC = 420, Halstead volume V = 1,800, G = 18.

AspectWalkthroughTechnical reviewInspection (Fagan)Pull-request review
Led byAuthorPeer/technical leadTrained moderatorReviewer(s) asynchronously
FormalityLowMediumHighestMedium, tool-enforced
Checklist and entry/exit criteriaOptionalUsuallyMandatoryTemplate plus CI gate
Metrics recordedRarelySometimesAlways (defects, effort, rate)Tool dashboards
Main purposeUnderstanding, trainingFitness for purposeDefect removalMerge decision, daily flow
Typical DRE20-35%35-50%50-70%40-60% with static analysis
SmellRefactoring that removes it
Long MethodExtract Method, Decompose Conditional
Duplicated CodeExtract Method / Pull Up Method, Extract Class
Large ClassExtract Class, Extract Subclass
Long Parameter ListIntroduce Parameter Object, Preserve Whole Object
Switch on typeReplace Conditional with Polymorphism
Deeply nested conditionalsReplace Nested Conditional with Guard Clauses
Message ChainsHide Delegate (Law of Demeter)
Magic numbersReplace Magic Number with Symbolic Constant

Where it is used

Interview questions

Common mistakes

Related topics

Software testing basics · Test automation and TDD · Design patterns · Low-level design (object-oriented design) interviews · Git and version control · Software architecture: monoliths and microservices

Open in the Knowledge reader →Find jobs →