Skip to content
KALANBLON
Show contents

Chapter 5 of 6 · 30 min

Project: a school's report cards

By the end of this chapter, you'll be able to

  • Validate data as soon as it is created with a record and its compact constructor
  • Turn format errors into precise messages, line by line
  • Compute nested averages with groupingBy and averagingDouble
  • Write tests without an external library, then know how to move them to JUnit

Step 1: the data and its rules

Each line of the file contains class;student;subject;mark, with marks out of 20. The rules:

  1. a line has exactly 4 fields;
  2. the mark is a number between 0 and 20;
  3. an invalid line is reported with its number, without stopping the processing;
  4. a class's average is the average of its students' averages.

A record's compact constructor (Mark { … }) runs before the fields are assigned: it's the ideal place to reject invalid data. An inconsistent Mark simply cannot exist.

Then the students' averages are grouped by class.

Step 7 of 7
Text description of the animation
  1. One line of the file.
  2. The line is split and the mark converted.
  3. The compact constructor accepts the mark.
  4. An unreadable mark is rejected with its line number.
  5. A mark of 21 is rejected by the record itself.
  6. Valid marks are grouped by student.
  7. Then the students' averages are grouped by class.

Step 2: the program and its tests

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

record Mark(String group, String student, String subject, double value) {
    Mark {
        if (value < 0 || value > 20) {
            throw new IllegalArgumentException("mark out of range: " + value);
        }
    }
}

Mark readMark(String line) {
    String[] f = line.split(";");
    if (f.length != 4) {
        throw new IllegalArgumentException("4 fields expected");
    }
    double value;
    try {
        value = Double.parseDouble(f[3]);
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("invalid mark: " + f[3]);
    }
    return new Mark(f[0], f[1], f[2], value);
}

List<Mark> load(Path file, List<String> errors) throws IOException {
    List<String> lines = Files.readAllLines(file);
    List<Mark> marks = new ArrayList<>();
    for (int i = 1; i < lines.size(); i++) {
        try {
            marks.add(readMark(lines.get(i)));
        } catch (IllegalArgumentException e) {
            errors.add("line " + (i + 1) + ": " + e.getMessage());
        }
    }
    return marks;
}

Map<String, Double> averagesPerStudent(List<Mark> marks) {
    return marks.stream()
        .collect(Collectors.groupingBy(Mark::student, TreeMap::new, Collectors.averagingDouble(Mark::value)));
}

Map<String, Double> averagesPerClass(List<Mark> marks) {
    Map<String, String> classOf = marks.stream()
        .collect(Collectors.toMap(Mark::student, Mark::group, (a, b) -> a));
    return averagesPerStudent(marks).entrySet().stream()
        .collect(Collectors.groupingBy(e -> classOf.get(e.getKey()), TreeMap::new,
            Collectors.averagingDouble(Map.Entry::getValue)));
}

void check(boolean condition, String message) {
    if (!condition) {
        throw new AssertionError(message);
    }
}

void runTests() {
    check(readMark("3A;Awa;maths;15").value() == 15, "reading a valid mark");
    try {
        readMark("3A;Awa;maths;25");
        check(false, "a mark of 25 should have been rejected");
    } catch (IllegalArgumentException e) {
        check(e.getMessage().contains("out of range"), "message for an out-of-range mark");
    }
    List<Mark> two = List.of(new Mark("3A", "Awa", "maths", 15), new Mark("3A", "Awa", "French", 13));
    check(averagesPerStudent(two).get("Awa") == 14.0, "a student's average");
    IO.println("Tests: OK");
}

void main() throws IOException {
    runTests();
    Path file = Files.createTempFile("marks", ".csv");
    Files.writeString(file, """
        class;student;subject;mark
        3A;Awa;maths;15
        3A;Awa;French;13
        3A;Chloé;maths;8
        3A;Chloé;French;11
        3B;Diego;maths;17
        3B;Diego;French;abc
        3B;Emeka;maths;12
        3B;Emeka;French;14
        3B;Fatou;maths;21
        """);
    List<String> errors = new ArrayList<>();
    List<Mark> marks = load(file, errors);
    Files.delete(file);

    errors.forEach(IO::println);
    IO.println("Ranking:");
    averagesPerStudent(marks).entrySet().stream()
        .sorted(Comparator.comparing((Map.Entry<String, Double> e) -> -e.getValue()).thenComparing(Map.Entry::getKey))
        .forEach(e -> IO.println(String.format("  %-6s %5.2f", e.getKey(), e.getValue())));
    averagesPerClass(marks).forEach((group, avg) -> IO.println(String.format("Class %s: %.2f", group, avg)));
}
Tests: OK
line 7: invalid mark: abc
line 10: mark out of range: 21.0
Ranking:
  Diego  17.00
  Awa    14.00
  Emeka  13.00
  Chloé   9.50
Class 3A: 11.75
Class 3B: 15.00

Choices worth noticing:

  • Two levels of validation. readMark checks the format (4 fields, a number), the record checks the business rules (between 0 and 20). Both throw IllegalArgumentException, caught once in load.
  • Line numbers are the file's (i + 1, the header being line 1): the office knows exactly what to fix.
  • A stable ranking: by decreasing average, then by name. Comparator.comparing(… -> -e.getValue()) sorts from largest to smallest.
  • Diego has only one valid mark: his average (17) rests on the only readable mark. A real report card would flag it, for instance by showing how many marks each student has.
  • check throws an AssertionError with a clear message. We don't use Java's assert keyword: it is disabled by default and only runs with the -ea option.

In a Maven or Gradle project, these tests are written with JUnit, which discovers and runs them automatically:

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class ReportCardTest {
    @Test
    void rejectsAnOutOfRangeMark() {
        var e = assertThrows(IllegalArgumentException.class, () -> ReportCard.readMark("3A;Awa;maths;25"));
        assertTrue(e.getMessage().contains("out of range"));
    }
}

Your turn

Worked exercise

Solved exercise: honours

Write a method Map<String, List<String>> honours(List<Mark> marks) that groups students by honours level according to their average: "highest honours" (16 and above), "high honours" (14 and above), "honours" (12 and above), "no honours" otherwise. Levels are sorted alphabetically, and each list contains the students' names. Use a simplified record Mark(String student, double value) where each student already has their average.

Hint 1
Collectors.groupingBy(key, TreeMap::new, downstream): the key is a conditional expression that returns the level's name.
Hint 2
The "downstream" collector Collectors.mapping(Mark::student, Collectors.toList()) keeps only the names in each group.
Show the solution and common mistakes
record Mark(String student, double value) {}

Map<String, List<String>> honours(List<Mark> marks) {
    return marks.stream().collect(Collectors.groupingBy(
        m -> m.value() >= 16 ? "highest honours" : m.value() >= 14 ? "high honours" : m.value() >= 12 ? "honours" : "no honours",
        TreeMap::new,
        Collectors.mapping(Mark::student, Collectors.toList())));
}

void main() {
    List<Mark> marks = List.of(new Mark("Awa", 14.0), new Mark("Chloé", 9.5), new Mark("Diego", 17.0), new Mark("Emeka", 13.0), new Mark("Lina", 16.0));
    honours(marks).forEach((level, students) -> IO.println(level + ": " + students));
}
high honours: [Awa]
highest honours: [Diego, Lina]
honours: [Emeka]
no honours: [Chloé]

Common mistakes:

  • Testing the thresholds in the wrong order (>= 12 first): every student above 12 gets "honours", Diego included.
  • Writing > 16 instead of >= 16: Lina, with exactly 16, would drop to "high honours".

Summary

  1. 1A record's compact constructor rejects invalid data as soon as it is created.
  2. 2Format validation (reading) is kept separate from business-rule validation (record).
  3. 3One error per line, with its number, without stopping the processing.
  4. 4groupingBy and averagingDouble compute nested averages in a few lines.
  5. 5Compare Double values with equals or a tolerance, never with ==.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.