PadhaikoAll subjects

Coding and Testing

Software Engineering (ENCT 352)

Open in the Padhaiko app

6.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

Essential Coding Standards and Best Practices
CategoryStandard / GuidelineEngineering Benefit
Naming ConventionsMeaningful camelCase / snake_case identifiers (studentCount over x1); constants in UPPER_SNAKE_CASESelf-documenting code; prevents variable shadowing
Formatting & IndentationConsistent indentation ( or spaces), line length limits ( chars), uniform brace placementEliminates visual clutter and noisy version-control diffs
Modularity & Function SizeKeep functions short, single-purpose, and shallowly nested (early returns over deep if/else ladders)Easier unit testing, reading, and reuse
Comments & DocstringsHeader docstrings describing contracts/parameters; inline comments explaining why, never obvious whatSpeeds up onboarding and prevents stale comments
Error Handling & SecurityNever silently swallow exceptions; validate all external inputs; avoid hardcoded secrets or raw SQL concatenationPrevents silent corruption, crashes, and injection flaws
Avoid Dangerous ConstructsAvoid goto, global mutable state, magic numbers, and overly clever side-effect expressionsReduces 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

6.2.2 Code inspection

AspectCode WalkthroughCode Inspection
FormalityInformal, flexible peer sessionFormal, rigorous, checklist-driven process
LeaderCode author presents the codeNeutral Moderator chairs; Reader paraphrases
PreparationMinimal advance studyMandatory individual preparation against checklists
Metrics & Follow-UpInformal notes; no defect-rate trackingFormal defect logs, root-cause tracking, verified rework

6.2.3 Cleanroom technique

Definition

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:

  1. Incremental Development under Statistical Quality Control: Software is built in certified increments.
  2. Formal Verification Over Ad-Hoc Debugging: Developers verify code correctness mathematically through structured team reviews ("Cleanroom inspections") before compiling or running it.
  3. 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

AspectVerificationValidation
Core Question"Are we building the product right?""Are we building the right product?"
FocusConformance of artifacts to specifications, design docs, and standardsConformance of the running software to real user needs and expectations
MethodsStatic reviews, walkthroughs, inspections, static analysis (no code execution needed)Dynamic execution: functional, system, and user acceptance testing
TimingThroughout every phase (SRS, design, code)Toward and after integration/system completion

6.3.2 Unit testing

6.3.3 Integration testing

Tests interfaces and data flow when individually tested units are combined into subsystems:

  1. Big-Bang Integration: Combine all modules at once and test; hard to isolate fault locations.
  2. Top-Down Integration: Start from the top control module and integrate downward (depth-first or breadth-first), using stubs for unbuilt lower modules.
  3. Bottom-Up Integration: Start from atomic leaf modules and integrate upward, using drivers to invoke lower clusters.
  4. 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:

6.3.5 Acceptance testing

Formal testing conducted to decide whether the customer will accept the delivered software:


6.4 Black-box and white-box testing approach

AspectBlack-Box TestingWhite-Box Testing
VisibilityTreats software as an opaque box; internal source code is ignoredExamines internal control flow, branches, loops, and data structures
Test BasisDerived from SRS, use cases, and input/output specificationsDerived from source code, control-flow graphs (CFG), and paths
Core TechniquesEquivalence Class Partitioning (ECP), Boundary Value Analysis (BVA), Decision Tables, State Transition TestingStatement Coverage, Branch/Decision Coverage, Condition Coverage, Basis Path Testing (Cyclomatic Complexity)
StrengthsCatches missing features and spec misunderstandings; scales to system/UATCatches dead code, hidden edge branches, loop off-by-one bugs

Key Black-Box Techniques

  1. 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.
  2. 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)

Definition

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).

The Red-Green-Refactor TDD CycleText
  +---> [ 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.

Automated Unit Test Example (AAA Pattern with unittest)Python
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

Definition

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

Example 6.1

6.1

A university grading module accepts two integer inputs: theoryMarks and practicalMarks .

  1. Compute the number of test cases generated by Standard Boundary Value Analysis (BVA) () and Robust BVA () for independent variables.
  2. List the exact boundary test values for theoryMarks under Robust BVA (choosing nominal value ) and define Equivalence Classes for theoryMarks.

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 practicalMarks held at nominal ):
  • Equivalence Classes for theoryMarks:
    • Invalid low: (e.g., )
    • Valid range: (e.g., )
    • Invalid high: (e.g., )
Answer:
  1. Standard BVA yields test cases (); Robust BVA yields test cases ().
  2. Robust BVA test inputs for theoryMarks are , partitioning the domain into invalid low (), valid (), and invalid high () equivalence classes.
Example 6.2

6.2

Consider the following Python function that validates a parcel shipping fee:

Parcel Shipping Fee CalculatorPython
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:

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):

  1. Path 1: (weight = 2, express = False fee = 50)
  2. Path 2: (weight = 8, express = False fee = 80)
  3. Path 3: (weight = 2, express = True fee = 110)
  4. Path 4: (weight = 12, express = True fee = 180)
Answer:

Cyclomatic Complexity is (), yielding independent basis paths: , , , and .

Example 6.3

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.

Answer:

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

Question 1

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

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.

Question 2

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:

  1. Unit Testing: Isolates individual functions/classes using stubs and drivers.
  2. Integration Testing: Verifies module interfaces (Top-Down, Bottom-Up, Big-Bang, Sandwich).
  3. System Testing: Tests the complete system end-to-end (functional, performance, stress, security, recovery).
  4. Acceptance Testing: Customer-focused validation—Alpha (at developer site) and Beta (at customer sites).
  5. Regression Testing: Re-runs tests after edits to catch unintended side effects.
Answer:

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.

Question 3

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

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.

Question 4
  1. 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.
  2. 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.
Answer:
  1. Cyclomatic complexity , requiring at least independent basis paths.
  2. For inputs, Standard BVA requires test cases and Robust BVA requires test cases.
Question 5

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):

  1. Red: Write a small automated unit test for a new behavior and watch it fail.
  2. Green: Write the simplest production code that makes the test pass.
  3. 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).
Answer:

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.

← System Modeling (part 2: 5.3–5.4)Software Quality, Assurance, Maintenance →