Results for “Records & reliable control flow”
Small, practical examples. Search by task or narrow things down below.
Define an immutable data record
Java: A local record gives a small Java data carrier named accessors and value semantics.
Java✓ Tested
Narrow an object with a pattern variable
Java: Pattern matching avoids a separate cast after a successful instanceof check.
Java✓ Tested
Represent a finite set of states
Java: Use an enum to prevent arbitrary strings from representing application states.
Java✓ Tested
Return a value from a switch expression
Java: Use an exhaustive switch expression with a fallback for other input values.
Java✓ Tested
Run a task on an executor and close it
Java: Java 21 ExecutorService supports try-with-resources to shut down after submitted work.
Java✓ Tested
Run cleanup after a handled exception
Java: A finally block executes whether the protected operation succeeds or fails.
Java✓ Tested
Transform an asynchronous result
Java: Chain thenApply and join a CompletableFuture to retrieve the completed value.
Java✓ Tested
Transform an optional value
Java: Use Optional.map and orElse to transform a possibly absent result.
Java✓ Tested
Update a shared counter atomically
Java: AtomicInteger provides an indivisible increment operation for a shared counter.
Java✓ Tested
Validate a required argument
Java: Use requireNonNull with a useful message at an API boundary.
Java✓ Tested
Create a modified copy of an immutable record
C#: A with expression creates a shallow copy with selected changed properties.
C#✓ Tested
Narrow an object using a type pattern
C#: A successful is pattern introduces a strongly typed local variable.
C#✓ Tested