Modularity separates software into components with focused responsibilities, so logic can be reused without dragging every dependency along for the ride. Decide where the concerns split early, then make that split part of the build. section 4.2.5 section 6.3.1
Take word-ladder validation to the web
Keep validation independent of HTTP. A ladder validator tokenizes the submitted data, checks the first word, and calls the existing word validator for each subsequent word. The server can then translate validation results into a 200 response or a 400 response with an error message. GET / serves the page, POST /ladder processes a ladder, and GET /first supplies a starting word. section 4.2.5
Listing 4.14 Validate ladder
fn validateLadder(ladder: []const u8) !void {
var word_iter = std.mem.tokenizeScalar(u8, ladder, '\n');
const first_word = word_iter.next() orelse {
return error.EmptyLadder; #1
};
if (first_word.len != 4) return error.BadLength;
var last_word: [4]u8 = first_word[0..4].*;
while (word_iter.next()) |raw_word| { #2
const word =
try validateWord(raw_word, last_word); #2
last_word = word;
}
}
The ladder validator composes the existing word validator rather than tying validation to a request handler. section 4.2.5
Keep a virtual machine lean
A CHIP-8 interpreter needs VM logic and an interactive runtime for keyboard input and graphical output. Put them in separate Zig modules: the runtime needs a heavier dependency that the VM does not, so VM tests can compile slightly faster without it. Zig modules start at a root source file and include its imports; dependencies are linked to modules. section 6.3.1
Listing 6.2 A more modular build script
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{}); #1
const optimize = b.standardOptimizeOption(.{}); #1
const vm_mod = b.createModule(.{ #2
.root_source_file = b.path("src/vm.zig"),
.target = target,
.optimize = optimize,
});
const test_mod = b.createModule(.{
.root_source_file = b.path("src/tests.zig"),
.target = target,
.optimize = optimize,
});
test_mod.addImport("vm", vm_mod); #3
}
The build script creates separate VM and test modules, then gives the test module an import of the VM. section 6.3.1
Listing 6.3 Making new steps
pub fn build(b: *std.Build) void {
// ... module code ...
const tests = b.addTest(.{ #1
.root_module = test_mod,
});
const run_tests = b.addRunArtifact(tests); #2
const test_cmd = b.step("test", "Run the vm tests"); #3
test_cmd.dependOn(&run_tests.step); #4
}
A test build step depends on running the test artifact, making the modular test setup directly runnable. section 6.3.1















