- Lab
-
Libraries: If you want this lab, consider one of these libraries.
Java Domain Models vs Ordinary Classes
The order service is the backend for a boutique online store. Its current domain layer is a pile of ordinary classes: a Money class with public setters, an OrderLine class that leaks its internal list, a tangle of if/instanceof checks for discount types, a PaymentType class that reads surcharge rates from a properties file every call, and a builder that was bolted on as a static method with mutable shared state. Support tickets keep citing negative prices, discount stacking bugs, and inconsistent receipts. You are modernizing this domain layer step by step so the compiler -- not code review -- enforces the business rules.
Lab Info
Table of Contents
-
Challenge
Tour the order domain layer
Welcome to the order service
The order service is the backend for a boutique online store, and its domain layer was assembled the way most Java domain layers grow: one ordinary class at a time, under deadline pressure.
Moneyhad public setters.OrderLinehanded out its internal list to anyone who asked. Discount logic was a wall ofinstanceofchecks that silently did nothing when it met a discount type nobody remembered to add a branch for.PaymentTypere-read a properties file from disk on every single call. The order builder was a static method with shared mutable state that two requests could stomp on at the same time. A migration to modern Java has started, and you are picking it up halfway.Support tickets keep citing the same three symptoms: negative prices that should have been impossible, discounts that stack when they should not, and receipts that disagree with each other for the same order. None of these are one-off bugs. They are the direct, predictable cost of modeling business rules with plain classes and hoping code review catches every violation. ### What went wrong, and what is in your workspace now
- Money used to be a mutable class with a public
setAmount, so anything holding a reference could push it negative. In your workspace it is already a record, but its compact constructor is a placeholder that throws, so nothing is validated yet. - LineItem (the old
OrderLine) is still a hand-written class. It stores aList<String>of tags and returns that exact list fromtags(), so a caller who adds to the returned list silently changes the line item. - Discount handling used to be a chain of
if (discount instanceof ...) ... else if (...)with noelsebranch, so a new discount type was evaluated as zero discount and nobody noticed until a refund request came in.Discountand its record implementations are in place, butDiscountis still an ordinary interface that anything can implement, andDiscountEvaluatorreturns zero for everything. - PaymentMethod replaces the old
PaymentType, which loadedsurcharge.propertiesfrom disk inside the surcharge calculation. A slow disk meant a slow checkout, and a missing file meant a crash. The enum constants are declared, but they carry no rates yet. - The order builder used to be a static factory method that mutated a shared
Listfield across calls, so two concurrent orders could merge their line items.Ordernow declares a static nestedBuilderand an innerReceiptPrinter, but neither does its job yet.
Each of these is a symptom of choosing the wrong tool: a mutable class where the data should be fixed at construction, an open type hierarchy where the set of cases should be closed and checked by the compiler, a hand-rolled cache where an enum constant already carries its own data. ### The plan
Over the next four steps you will rebuild this domain layer piece by piece, and each piece reaches for the Java SE 21 construct that actually fits the rule it enforces:
- Step 2 -
Moneygets a validating compact constructor, andLineItemis rewritten from a hand-written class into a record that validates its own inputs and stays shallowly immutable even though it holds a collection. - Step 3 -
Discountbecomes a sealed interface with a closed set of implementations, plus one deliberate non-sealed extension point for aLoyaltyDiscountthat a future team can add without touching the sealed contract. - Step 4 - the
instanceofchain is replaced with an exhaustive switch expression over the sealed hierarchy, using record deconstruction patterns, so a missing case is a compile error instead of a silent zero. - Step 5 - each
PaymentMethodconstant carries its own surcharge rate, cached once in anEnumMap, andOrderpicks a static nested class for its builder and an inner class for a receipt printer that reads the order's live state.
By the end, the compiler enforces the rules that code review used to miss.
- Money used to be a mutable class with a public
-
Challenge
Replace Money and LineItem with validated records
Records and compact constructors
A Java
recordgives you a constructor, accessors,equals,hashCode, andtoStringfor free, but the real win for a domain model is the compact constructor: a constructor body with no parameter list that runs before the fields are assigned, where you can validate or normalize the incoming values. Throw from there and an invalidMoneycan never exist. It is not that one "probably won't" exist; it structurally cannot.src/main/java/lab/Money.javaalready declares the record shape; its compact constructor is still a placeholder that throws, so noMoneycan be created at all until you fill it in. ### Shallow immutability and defensive copyingA record's fields are final, but that only makes the reference immutable. If a field holds a
List, the record is still exposed to anyone who holds a reference to that same list and mutates it out from under you. This is "shallow" immutability: the record itself cannot reassign the field, but the object it points to can still change unless you copy it. The fix is to copy the incoming collection into an unmodifiable one inside the compact constructor, so the record's view of it can never drift.src/main/java/lab/LineItem.javais still the hand-written class it is meant to replace: fields, a constructor, accessors,equals,hashCodeandtoString, and atags()that returns the caller's own list. As a record it shrinks to a header, a compact constructor andlineTotal(). ### Putting the validated records to workNow that
Moneycannot be negative andLineItemcannot leak its tags, the order total calculation insrc/main/java/lab/Order.javacan lean on those guarantees instead of re-checking them. EachLineItemalready knows how to compute its own line total;computeTotal()just needs to fold all of them into oneMoneyusing the addition you can now trust. -
Challenge
Close the Discount hierarchy with sealed types
Sealed interfaces close the set of cases
The old discount code broke because
Discountwas an ordinary interface: anyone could implement it, so theinstanceofchain evaluating discounts could never know it had covered every case. Asealed interface Discount permits PercentageDiscount, FixedAmountDiscount, CustomDiscountfixes that at compile time. Only the types named inpermits(or types that themselves extend one of them) can implementDiscountat all.src/main/java/lab/Discount.javais still an ordinary interface.PercentageDiscountandFixedAmountDiscountare already validated records, so sealing the interface is what is left to close the hierarchy. ### Deliberate extension points with non-sealed subtypesSealing everything would mean nobody could ever add a new kind of discount without editing
Discount.javaitself. That is why the permits list also namesCustomDiscount, which you just markednon-sealed. It is the one door left deliberately open. Removenon-sealedagain and the compiler rejectsCustomDiscount: both the closed and the open parts of the hierarchy are enforced, not just documented. Anything implementingCustomDiscountjoins theDiscountfamily without touching the sealed contract, which is exactly howsrc/main/java/lab/LoyaltyDiscount.javaplugs in a business rule that did not exist whenDiscountwas first sealed. It already implementsCustomDiscount; it still needs its rules and itsamountOff. -
Challenge
Evaluate discounts with exhaustive pattern matching
Exhaustive switch pattern matching
With
Discountsealed, aswitchexpression over it can be checked by the compiler for exhaustiveness. Add a new permitted type later and any switch missing a case for it fails to compile, instead of silently returning the wrong answer the way the oldinstanceofchain did. Record deconstruction patterns let a case pull a discount's fields straight out of the pattern, as incase PercentageDiscount(var rate) ->, with no manual accessor calls.src/main/java/lab/DiscountEvaluator.javaneeds itsevaluatemethod built this way. ### Folding a list of cases into one resultA single
evaluatecall handles one discount, but a real order can carry several stacked discounts. Fold the list: start from a zero value and combine one discount's result into the running total at a time. This reusesevaluatefor every entry without needing a second switch.totalDiscount, right belowevaluatein the same file, needs that fold. ### Wiring the discount total into the orderOrder.computeTotal()from Step 2 gives you the subtotal;DiscountEvaluator.totalDiscount()now gives you the combined discount for that subtotal.finalTotal()insrc/main/java/lab/Order.javajust needs to combine the two, which is the moment the sealed-and-switched discount hierarchy actually changes what a customer pays. -
Challenge
Wire payments and nested types into the finished order
Enums that carry data and behavior
An
enumconstant in Java is not just a labeled integer. Each constant is a full object that can carry its own fields through a constructor, and the enum type can hold static state like anEnumMapkeyed by its own constants, plus instance methods that use it. That replaces the old properties-file lookup with data that is loaded once and read in memory on every call.src/main/java/lab/PaymentMethod.javadeclaresCREDIT_CARD,DEBIT_CARD,PAYPAL, andBANK_TRANSFERand an emptySURCHARGE_RATESmap; the constants need their rates, the map needs filling once, andsurchargeForneeds to read it. ### Static nested classes vs inner classesJava gives you two different nested-class shapes for two different needs. A static nested class does not carry a reference to an enclosing instance, which makes it the right shape for a builder: it accumulates its own state and produces a brand-new
Orderat the end, with no shared mutable field like the old static-method builder had.src/main/java/lab/Order.javadeclaresBuilderas exactly that; itsbuild()method still needs to assemble theOrderit promises. ### Inner classes read the enclosing instance's live stateAn inner class, by contrast, holds an implicit reference to the enclosing instance, which is exactly what you want when the nested type's whole job is to report on that instance's current state.
Order.ReceiptPrinteris declared as a non-static inner class for that reason: it can callcomputeTotal(),finalTotal(), and readpaymentMethodstraight off the enclosingOrderwithout you passing anything in.printReceipt()still needs to turn that state into the receipt text. -
Challenge
See the domain model enforce its own rules
See the domain model enforce its own rules
Now run the whole order flow once, watch the domain objects refuse bad values, and then see the compiler reject a switch that misses a case.
1. Print a real receipt
In the Terminal tab, run:
bash runApp.shsrc/main/java/lab/Main.javabuilds one order: two silk scarves at 45.00, a pair of gloves at 30.00, a 10%PercentageDiscount, a 5%LoyaltyDiscount, andPAYPALas the payment method. The first section of the output is its receipt:Subtotal: Money[amount=120.00, currency=USD] Discount: Money[amount=18.0000, currency=USD] Surcharge: Money[amount=3.060000, currency=USD] Total: Money[amount=105.060000, currency=USD]Every line passes through code you wrote. Your
Builderfrom Task 5.2 assembled the order, and yourReceiptPrinterfrom Task 5.3 read its totals straight off that order. The 18.0000 discount is 12.00 from the percentage case of your Task 4.1 switch plus 6.00 fromLoyaltyDiscount, which reached the same switch through theCustomDiscountcase without ever being listed inDiscount's permits clause. The 3.06 surcharge is PayPal's 3% of the discounted 102.00, read from theEnumMapyou filled in Task 5.1. The currency went in as"usd"and comes out asUSDbecause your compact constructor normalized it. ### 2. Watch bad values get refusedThe second section of the same output tries to create objects the business rules forbid:
Rejected: Money of -5.00 -> Amount must not be negative Rejected: LineItem with quantity 0 -> quantity must be positive Rejected: LoyaltyDiscount at 60% -> rate must be greater than 0 and at most 0.5 Rejected: Order with no line items -> Order must have at least one line item Caller added "clearance" to its own list; the line item's tags are still [accessory]The messages are the ones you wrote, so your wording may differ. What matters is that every line says
Rejected. The oldMoneywould have quietly held -5.00, and the oldOrderLinewould have shown the caller'sclearancetag because it handed out the caller's own list. Now your compact constructors (Tasks 2.1, 2.2 and 3.2) andbuild()(Task 5.2) refuse each value before the object exists, and the copy you made in Task 2.2 keeps the line item's tags its own. If a line saysAccepted, that rule is missing. ### 3. Let the compiler catch a missing caseThe old
instanceofchain returned zero discount for any type nobody remembered to handle. To see why your switch can't do that, opensrc/main/java/lab/DiscountEvaluator.javaand delete this line fromevaluate:case CustomDiscount cd -> cd.amountOff(subtotal);Rerun the
bash runApp.shcommand. This time the program doesn't build, and Maven points at yourswitchline (the line and column numbers depend on your file):[ERROR] .../DiscountEvaluator.java:[20,16] the switch expression does not cover all possible input valuesYou sealed
Discountin Task 3.1 and left out adefaultbranch in Task 4.1, so the compiler knows every case that exists and rejects a switch that skips one. Put the line back andbash runApp.shprints the receipt again.That's the lab: the rules that support tickets used to catch after the fact are now enforced when an object is created, or when the code compiles.
Congratulations on completing this lab!
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.