Skip to main content

Aggregation and Invariants

What this concept is​

Aggregation combines records into a summary. An invariant is a statement that should remain true while you process them. For a total, the accumulator equals the sum of the processed records; for a group map, each topic holds the sum for that topic so far.

Why it matters here​

A report can be syntactically valid and still count the wrong thing. Invariants give you checks that are independent of how attractive the output looks.

Concrete example​

Records with minutes 25, 15, 25 and 10 have count 4 and total 75. If the middle two records are both Python, their topic total is 40. The sum of all topic totals must equal 75. Two identical records Python,25 represent two sessions: count 2, total 50. Converting the records or durations to a set changes the meaning.

When a new topic appears, initialize its group total to zero before adding minutes. A dictionary's get(topic, 0) expresses that default; it does not imply a missing input record has zero duration.

Common confusion / misconception​

Count and total are not interchangeable. An average requires a denominator and an empty-case decision. Sorting the report may improve reproducibility but must not silently remove duplicates or mutate input records.

How to use it​

State the input assumption: aggregation receives validated records. Test empty input, one row, repeated rows and multiple topics. Check that the input is unchanged. Add the invariant “sum of grouped totals equals overall total.” Then check a manually calculated expected output: two incorrect computations could agree with each other.

Check yourself​

Does a matching grouped sum prove the report is correct? No. Both calculations could skip the same record. An independent expected example and boundary cases remain necessary.

Mini drill or application​

Add a new valid row to a copy of the input. Predict the increment to count, overall total and the affected topic. Verify all three and explain why unrelated topic totals remain unchanged.

Read this only if stuck​

Python dictionaries supports the group map. The invariants come from the stated reporting requirement.