Implementation
implementation
Code Snippets
Java Record for Lightweight DTOs
Records (Java 14 preview, stable since Java 16) collapse boilerplate immutable data carriers into one line. This snippet shows the canonical record, a compact constructor for validation, and using records as map keys. The runnable code targets Java 13 syntax (since the test runner is OpenJDK 13), with the modern record equivalent shown inline in comments and explanations.
Stream toList Collector
Collecting a stream into a `List` is the most common terminal operation in modern Java. This snippet shows the three idiomatic options: the legacy `Collectors.toList()`, the unmodifiable `Collectors.toUnmodifiableList()` (Java 10+), and the convenient `Stream.toList()` shortcut (Java 16+). Pick the unmodifiable variant for return values to prevent caller mutation.
Optional orElseGet Patterns
`Optional` makes the absence of a value explicit, but the `orElse` vs `orElseGet` choice trips people up. This snippet contrasts the two, shows `orElseThrow` for required-value contracts, and demonstrates `map`/`flatMap` chaining for null-safe field access. Reach for `orElseGet` whenever the default is expensive to compute.
Group by Key with Stream Collectors
`Collectors.groupingBy` is the Java equivalent of SQL `GROUP BY`: pass a key extractor and you get back a `Map<K, List<T>>`. This snippet covers the basic grouping, downstream collectors (counting, summing, mapping to a different value), and multi-level grouping by chaining two `groupingBy` calls. Pair with `LinkedHashMap` when you need stable insertion order.
Idiomatic Go Error Handling
Go has no exceptions; errors are values returned alongside the result. This snippet covers the canonical `if err != nil` check, error wrapping with `fmt.Errorf("...: %w", err)` (Go 1.13+) for context, and unwrapping with `errors.Is` / `errors.As` to inspect underlying error types. Get this right and your stack of error returns will read as cleanly as any try/catch.
Go Slice Operations Cheat Sheet
Slices are Go's dynamic array: a (pointer, length, capacity) header pointing into a backing array. This snippet covers the common operations: `append` and capacity growth, `copy` between slices, reslicing pitfalls (sharing the backing array), and a clean way to delete an element from the middle. Understand the header model and surprising slice aliasing bugs become obvious.
