Coding and Testing
Open in the Padhaiko app6.1 Coding standards and guidelines
Coding standards are agreed-upon rules and conventions governing source code style, structure, and safety so that a codebase looks as though it were written by a single disciplined engineer.
Core Coding Standards & Guidelines
| Category | Standard / Guideline | Engineering Benefit |
|---|---|---|
| Naming Conventions | Meaningful camelCase / snake_case identifiers (studentCount over x1); constants in UPPER_SNAKE_CASE | Self-documenting code; prevents variable shadowing |
| Formatting & Indentation | Consistent indentation ( or spaces), line length limits ( chars), uniform brace placement | Eliminates visual clutter and noisy version-control diffs |
| Modularity & Function Size | Keep functions short, single-purpose, and shallowly nested (early returns over deep if/else ladders) | Easier unit testing, reading, and reuse |
| Comments & Docstrings | Header docstrings describing contracts/parameters; inline comments explaining why, never obvious what | Speeds up onboarding and prevents stale comments |
| Error Handling & Security | Never silently swallow exceptions; validate all external inputs; avoid hardcoded secrets or raw SQL concatenation | Prevents silent corruption, crashes, and injection flaws |
| Avoid Dangerous Constructs | Avoid goto, global mutable state, magic numbers, and overly clever side-effect expressions | Reduces hidden coupling and subtle runtime bugs |
6.2 Code review
Code review is a static quality-assurance activity (performed without executing the program) in which peers examine source code to detect logic flaws, standard violations, edge-case omissions, and security issues early.
6.2.1 Code walkthrough
- Informal peer review led by the author of the code, who walks colleagues line-by-line through a module or design snippet.
- Goal: Knowledge sharing, catching obvious logic errors, and validating design alignment in a collaborative, non-evaluative setting.
- Process: Minimal preparation overhead; little formal documentation beyond informal notes for the author to resolve.
6.2.2 Code inspection
- Formal, structured, checklist-driven review (introduced by Michael Fagan) designed specifically to maximize defect detection.
- Roles: Moderator (chairs the meeting, enforces pace), Author (answers questions without defending code), Reader (paraphrases code aloud), Inspectors (hunt for defects using checklists), and Scribe (logs every defect).
- Process Phases: Planning Overview Individual Preparation Inspection Meeting Rework Follow-up.
- Goal: Uncover defects systematically (e.g., off-by-one loops, null-pointer dereferences, resource leaks, uninitialized variables) using metrics like defect density.
| Aspect | Code Walkthrough | Code Inspection |
|---|---|---|
| Formality | Informal, flexible peer session | Formal, rigorous, checklist-driven process |
| Leader | Code author presents the code | Neutral Moderator chairs; Reader paraphrases |
| Preparation | Minimal advance study | Mandatory individual preparation against checklists |
| Metrics & Follow-Up | Informal notes; no defect-rate tracking | Formal defect logs, root-cause tracking, verified rework |
6.2.3 Cleanroom technique
Cleanroom Software Engineering
The Cleanroom technique (pioneered by Harlan Mills) is a disciplined engineering approach aimed at preventing defects before testing through formal mathematical specification, stepwise refinement, box-structure modeling, formal correctness verification (peer proof), and statistical usage testing—without developer-run unit debugging.
Key pillars of Cleanroom engineering:
- Incremental Development under Statistical Quality Control: Software is built in certified increments.
- Formal Verification Over Ad-Hoc Debugging: Developers verify code correctness mathematically through structured team reviews ("Cleanroom inspections") before compiling or running it.
- Statistical Usage Testing: An independent test team generates test cases sampled from the software's expected operational usage profile to certify reliability (Mean Time To Failure) rather than hunting bugs via ad-hoc trial-and-error.
6.3 Software testing fundamentals
Software testing is the process of executing a program with the intent of finding errors and demonstrating that the software meets its specified requirements. As Dijkstra famously noted, "Testing shows the presence, not the absence of bugs."
6.3.1 Verification and validation
| Aspect | Verification | Validation |
|---|---|---|
| Core Question | "Are we building the product right?" | "Are we building the right product?" |
| Focus | Conformance of artifacts to specifications, design docs, and standards | Conformance of the running software to real user needs and expectations |
| Methods | Static reviews, walkthroughs, inspections, static analysis (no code execution needed) | Dynamic execution: functional, system, and user acceptance testing |
| Timing | Throughout every phase (SRS, design, code) | Toward and after integration/system completion |
6.3.2 Unit testing
- Tests the smallest testable piece of software—a single function, method, or class—in isolation from external dependencies.
- Because a unit rarely runs standalone, engineers use test scaffolding:
- Driver: A dummy main module that calls the unit under test with sample inputs and checks its return value.
- Stub: A dummy replacement for a lower-level module called by the unit under test, returning canned responses.
6.3.3 Integration testing
Tests interfaces and data flow when individually tested units are combined into subsystems:
- Big-Bang Integration: Combine all modules at once and test; hard to isolate fault locations.
- Top-Down Integration: Start from the top control module and integrate downward (depth-first or breadth-first), using stubs for unbuilt lower modules.
- Bottom-Up Integration: Start from atomic leaf modules and integrate upward, using drivers to invoke lower clusters.
- Sandwich (Hybrid) Integration: Combines top-down and bottom-up approaches simultaneously toward a middle layer.
6.3.4 System testing
Tests the completely integrated system end-to-end against both functional and non-functional requirements in an environment closely mirroring production. Major system testing types include:
- Performance & Load Testing: Measures throughput and response time under expected and peak user traffic.
- Stress Testing: Pushes the system beyond design limits (memory, CPU, concurrency) to verify graceful degradation.
- Security Testing: Probes authentication, authorization, input sanitization, and encryption.
- Recovery & Reliability Testing: Forces crashes, disk failures, or network drops to verify data integrity and recovery time.
6.3.5 Acceptance testing
Formal testing conducted to decide whether the customer will accept the delivered software:
- Alpha Testing: Conducted at the developer's site by a representative group of end users under controlled observation.
- Beta Testing: Conducted at real customer sites in live environments without developer supervision, uncovering environment-specific bugs and usability issues before general release.
- User Acceptance Testing (UAT): Customer-executed validation against contract acceptance criteria before final sign-off.
6.4 Black-box and white-box testing approach
| Aspect | Black-Box Testing | White-Box Testing |
|---|---|---|
| Visibility | Treats software as an opaque box; internal source code is ignored | Examines internal control flow, branches, loops, and data structures |
| Test Basis | Derived from SRS, use cases, and input/output specifications | Derived from source code, control-flow graphs (CFG), and paths |
| Core Techniques | Equivalence Class Partitioning (ECP), Boundary Value Analysis (BVA), Decision Tables, State Transition Testing | Statement Coverage, Branch/Decision Coverage, Condition Coverage, Basis Path Testing (Cyclomatic Complexity) |
| Strengths | Catches missing features and spec misunderstandings; scales to system/UAT | Catches dead code, hidden edge branches, loop off-by-one bugs |
Key Black-Box Techniques
- Equivalence Class Partitioning (ECP): Divide the input domain into valid and invalid equivalence classes where any value in a class behaves identically, picking one representative per class.
- Boundary Value Analysis (BVA): Defects cluster at boundaries! For an input range , test (or standard 5-point BVA yielding test cases for independent variables; robust BVA with out-of-bounds values yields cases).
Key White-Box Technique: Basis Path Testing (McCabe)
Given a Control Flow Graph (CFG) with edges, nodes, and predicate (decision) nodes, McCabe's Cyclomatic Complexity gives the upper bound on the number of linearly independent paths required for full branch coverage:
6.5 Agile testing practices
In agile teams, testing is not a separate late-stage phase ("throw it over the wall to QA")—quality is built continuously into every sprint by developers and testers working together.
6.5.1 Test-driven development (TDD)
Test-Driven Development (TDD)
Test-Driven Development (TDD) is an evolutionary programming workflow in which the developer writes a failing automated unit test first, writes the minimal production code needed to pass it, and then refactors the code while keeping all tests green (Red–Green–Refactor).
+---> [ 1. RED: Write a failing unit test for one small requirement ]
| |
| v
| [ 2. GREEN: Write minimal code to make the test pass ]
| |
| v
+---- [ 3. REFACTOR: Clean up duplication & design; re-run tests ]6.5.2 Continuous testing
Continuous testing integrates automated unit, integration, API, and UI tests directly into the Continuous Integration (CI) pipeline so that every code commit triggers immediate test execution, providing rapid feedback on regressions within minutes rather than weeks.
6.5.3 Automated unit testing basics
Automated unit tests are fast, deterministic, self-verifying scripts organized around the Arrange–Act–Assert (AAA) pattern using xUnit frameworks (pytest, JUnit, Jest). Tests use mocks/fakes for slow external resources (databases, network APIs) so thousands of tests run in seconds.
import unittest
def compute_discount(total: float, is_member: bool) -> float:
if total < 0:
raise ValueError("Total cannot be negative")
rate = 0.10 if is_member and total >= 100 else 0.0
return total * (1.0 - rate)
class TestDiscount(unittest.TestCase):
def test_member_eligible_for_discount(self):
# Arrange & Act
payable = compute_discount(200.0, is_member=True)
# Assert
self.assertAlmostEqual(payable, 180.0)6.5.4 Refactoring for code quality
Refactoring
Refactoring (Martin Fowler) is the disciplined process of restructuring internal software design to improve readability, reduce duplication, and lower complexity without altering its observable external behavior.
Common code smells (symptoms signaling the need to refactor) include duplicated code, long methods, large ("God") classes, long parameter lists, and deeply nested conditionals. Common refactoring moves include Extract Method, Rename Variable/Method, Replace Magic Number with Named Constant, and Decompose Conditional—all protected by running automated unit tests after every small edit.
Worked Examples
6.1
A university grading module accepts two integer inputs: theoryMarks and practicalMarks .
- Compute the number of test cases generated by Standard Boundary Value Analysis (BVA) () and Robust BVA () for independent variables.
- List the exact boundary test values for
theoryMarksunder Robust BVA (choosing nominal value ) and define Equivalence Classes fortheoryMarks.
Part 1 — Compute BVA Test Case Counts ():
- Standard BVA tests for one variable while holding the other at nominal:
- Robust BVA adds and to verify invalid boundary rejection:
Part 2 — Robust BVA Values & Equivalence Classes for theoryMarks :
- Robust BVA values (with
practicalMarksheld at nominal ):
- Equivalence Classes for
theoryMarks:- Invalid low: (e.g., )
- Valid range: (e.g., )
- Invalid high: (e.g., )
- Standard BVA yields test cases (); Robust BVA yields test cases ().
- Robust BVA test inputs for
theoryMarksare , partitioning the domain into invalid low (), valid (), and invalid high () equivalence classes.
6.2
Consider the following Python function that validates a parcel shipping fee:
def shipping_fee(weight, express): # Node 1 (Entry)
fee = 50 # Node 1
if weight > 5: # Node 2 (Decision 1)
fee += 30 # Node 3
if express: # Node 4 (Decision 2)
if weight > 10: # Node 5 (Decision 3)
fee += 100 # Node 6
else:
fee += 60 # Node 6 (alt branch merges to Node 7)
return fee # Node 7 (Exit)Wait—let us trace the exact Control Flow Graph nodes and edges carefully:
- Let Node = entry +
fee = 50+if weight > 5? More clearly, number each basic block/decision:- :
fee = 50; if weight > 5(edges to [T] and [F]) - :
fee += 30(edge to ) - :
if express(edges to [T] and [F]) - :
if weight > 10(edges to [T] and [F]) - :
fee += 100(edge to ) - :
fee += 60(edge to ) - :
return fee
- :
Given this CFG with nodes, directed edges, and binary predicate nodes (), compute McCabe's Cyclomatic Complexity using both formulas and list a complete basis set of independent paths.
Verify Edge and Node Counts in the CFG:
- Nodes (): .
- Edges (): .
- Binary decision predicates ():
weight > 5(),express(),weight > 10().
Compute Cyclomatic Complexity : Using :
Using :
Both formulas agree: linearly independent paths are required for basis path coverage.
Enumerate the Independent Basis Paths (with Sample Test Cases):
- Path 1: (
weight = 2, express = Falsefee = 50) - Path 2: (
weight = 8, express = Falsefee = 80) - Path 3: (
weight = 2, express = Truefee = 110) - Path 4: (
weight = 12, express = Truefee = 180)
Cyclomatic Complexity is (), yielding independent basis paths: , , , and .
6.3
How to Answer a Past Exam Question: "Compare Top-Down and Bottom-Up Integration Testing, explaining the exact role of Stubs and Drivers."
1. Define Both Strategies and Their Scaffolding:
- Top-Down Integration: Begins at the main control module and integrates downward layer by layer. Unfinished lower-level modules are temporarily simulated by stubs (dummy callees returning canned values).
- Bottom-Up Integration: Begins at low-level utility/leaf modules and integrates upward into clusters. Unfinished higher-level callers are simulated by drivers (dummy callers invoking the cluster with test inputs).
2. Highlight Pros/Cons in a Crisp Exam Table: Note that Top-Down verifies major architectural control early (and works well for early UI demos) without needing drivers, whereas Bottom-Up avoids writing complex stubs and tests low-level I/O/algorithms thoroughly early. Mention Sandwich (Hybrid) Testing as the practical combination.
Top-down integration starts from the root module using stubs for missing callees; bottom-up integration starts from leaf modules using drivers for missing callers. State their complementary strengths and note hybrid sandwich testing.
Exercises
Practice Exercises — Coding & Testing
Why are coding standards and guidelines important in team software projects? Compare Code Walkthrough, Code Inspection, and the Cleanroom technique.
Importance of Coding Standards: Consistent naming, formatting, modularity, error handling, and documentation reduce cognitive friction, prevent security/logic defects, minimize noisy version-control diffs, and make maintenance fast across changing team members.
Comparison of Review & Cleanroom Approaches:
- Code Walkthrough: Informal author-led peer session for shared understanding and quick feedback.
- Code Inspection: Formal, checklist-driven, role-based review (Moderator, Reader, Author, Inspectors, Scribe) with formal defect logging and verified rework.
- Cleanroom Technique: Replaces developer trial-and-error debugging with formal mathematical verification (box structures, peer correctness proofs) and statistical usage testing against an operational profile.
Coding standards enforce uniform, readable, secure code across teams. Walkthroughs are informal author-led reviews, Inspections are formal checklist-based defect hunts with defined roles, and Cleanroom relies on mathematical verification and statistical usage testing rather than ad-hoc debugging.
Distinguish between Verification and Validation, and briefly explain the five testing levels: Unit, Integration, System, Acceptance (Alpha & Beta), and Regression testing.
Verification vs. Validation:
- Verification ("Are we building the product right?"): Static checks (reviews, inspections) confirming artifacts match specifications.
- Validation ("Are we building the right product?"): Dynamic execution confirming software satisfies real user needs.
Testing Levels:
- Unit Testing: Isolates individual functions/classes using stubs and drivers.
- Integration Testing: Verifies module interfaces (Top-Down, Bottom-Up, Big-Bang, Sandwich).
- System Testing: Tests the complete system end-to-end (functional, performance, stress, security, recovery).
- Acceptance Testing: Customer-focused validation—Alpha (at developer site) and Beta (at customer sites).
- Regression Testing: Re-runs tests after edits to catch unintended side effects.
Verification checks conformance to specification (building it right), while Validation checks fitness for user intent (building the right thing). Software progresses through Unit Integration System Acceptance (Alpha/Beta) testing, backed continuously by Regression testing.
Differentiate between Black-Box and White-Box testing. Explain Equivalence Class Partitioning (ECP) and Boundary Value Analysis (BVA) with a brief example.
Black-Box vs. White-Box Testing: Black-box testing derives test cases solely from external specifications without reading source code, whereas white-box testing inspects internal code structure (statements, branches, paths) to ensure structural coverage.
ECP and BVA Example (Age Field ):
- ECP splits inputs into three partitions—valid (pick ), invalid low (pick ), invalid high (pick ).
- BVA targets edge values where
<vs<=bugs hide: .
Black-box testing tests functional behavior from specifications; white-box testing tests internal code structure. ECP picks one representative per equivalence class, while BVA focuses test cases directly on and adjacent to partition boundaries.
- A module's Control Flow Graph (CFG) has nodes, edges, and binary decision predicates. Compute McCabe's Cyclomatic Complexity using both formulas and state the minimum number of independent basis paths needed.
- A web form accepts independent numeric fields. Calculate the number of test cases required under Standard BVA () and Robust BVA ().
Part 1 — Cyclomatic Complexity:
At least linearly independent basis paths must be tested.
Part 2 — BVA Test Case Counts ():
- Standard BVA: test cases.
- Robust BVA: test cases.
- Cyclomatic complexity , requiring at least independent basis paths.
- For inputs, Standard BVA requires test cases and Robust BVA requires test cases.
Explain the Red–Green–Refactor cycle of Test-Driven Development (TDD), describe continuous testing, and explain how refactoring differs from rewriting or bug fixing.
TDD (Red–Green–Refactor):
- Red: Write a small automated unit test for a new behavior and watch it fail.
- Green: Write the simplest production code that makes the test pass.
- Refactor: Clean up duplication and improve structure while all tests stay green.
Continuous Testing & Refactoring:
- Continuous Testing runs automated test suites on every commit inside a CI pipeline so regressions are caught within minutes.
- Refactoring improves internal code design (clarity, modularity, zero duplication) without changing external observable behavior, unlike bug fixing (which changes faulty behavior) or rewriting (which discards existing code).
TDD cycles through Red (failing test), Green (minimal passing code), and Refactor (clean internal design). Continuous testing runs automated tests on every CI commit, and refactoring improves internal code quality while preserving external behavior.