Featured resource
2026 Tech Forecast
2026 Tech Forecast

1,500+ tech insiders, business leaders, and Pluralsight Authors share their predictions on what’s shifting fastest and how to stay ahead.

Download the forecast
  • Lab
    • Libraries: If you want this lab, consider one of these libraries.
Labs

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 platform
Lab Info
Level
Intermediate
Last updated
Dec 03, 2026
Duration
1h 0m

Contact sales

By clicking submit, you agree to our Privacy Policy and Terms of Use, and consent to receive marketing emails from Pluralsight.
Table of Contents
  1. 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. Money had public setters. OrderLine handed out its internal list to anyone who asked. Discount logic was a wall of instanceof checks that silently did nothing when it met a discount type nobody remembered to add a branch for. PaymentType re-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 a List<String> of tags and returns that exact list from tags(), 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 no else branch, so a new discount type was evaluated as zero discount and nobody noticed until a refund request came in. Discount and its record implementations are in place, but Discount is still an ordinary interface that anything can implement, and DiscountEvaluator returns zero for everything.
    • PaymentMethod replaces the old PaymentType, which loaded surcharge.properties from 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 List field across calls, so two concurrent orders could merge their line items. Order now declares a static nested Builder and an inner ReceiptPrinter, 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:

    1. Step 2 - Money gets a validating compact constructor, and LineItem is rewritten from a hand-written class into a record that validates its own inputs and stays shallowly immutable even though it holds a collection.
    2. Step 3 - Discount becomes a sealed interface with a closed set of implementations, plus one deliberate non-sealed extension point for a LoyaltyDiscount that a future team can add without touching the sealed contract.
    3. Step 4 - the instanceof chain 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.
    4. Step 5 - each PaymentMethod constant carries its own surcharge rate, cached once in an EnumMap, and Order picks 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.

  2. Challenge

    Replace Money and LineItem with validated records

    Records and compact constructors

    A Java record gives you a constructor, accessors, equals, hashCode, and toString for 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 invalid Money can never exist. It is not that one "probably won't" exist; it structurally cannot. src/main/java/lab/Money.java already declares the record shape; its compact constructor is still a placeholder that throws, so no Money can be created at all until you fill it in. ### Shallow immutability and defensive copying

    A 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.java is still the hand-written class it is meant to replace: fields, a constructor, accessors, equals, hashCode and toString, and a tags() that returns the caller's own list. As a record it shrinks to a header, a compact constructor and lineTotal(). ### Putting the validated records to work

    Now that Money cannot be negative and LineItem cannot leak its tags, the order total calculation in src/main/java/lab/Order.java can lean on those guarantees instead of re-checking them. Each LineItem already knows how to compute its own line total; computeTotal() just needs to fold all of them into one Money using the addition you can now trust.

  3. Challenge

    Close the Discount hierarchy with sealed types

    Sealed interfaces close the set of cases

    The old discount code broke because Discount was an ordinary interface: anyone could implement it, so the instanceof chain evaluating discounts could never know it had covered every case. A sealed interface Discount permits PercentageDiscount, FixedAmountDiscount, CustomDiscount fixes that at compile time. Only the types named in permits (or types that themselves extend one of them) can implement Discount at all. src/main/java/lab/Discount.java is still an ordinary interface. PercentageDiscount and FixedAmountDiscount are already validated records, so sealing the interface is what is left to close the hierarchy. ### Deliberate extension points with non-sealed subtypes

    Sealing everything would mean nobody could ever add a new kind of discount without editing Discount.java itself. That is why the permits list also names CustomDiscount, which you just marked non-sealed. It is the one door left deliberately open. Remove non-sealed again and the compiler rejects CustomDiscount: both the closed and the open parts of the hierarchy are enforced, not just documented. Anything implementing CustomDiscount joins the Discount family without touching the sealed contract, which is exactly how src/main/java/lab/LoyaltyDiscount.java plugs in a business rule that did not exist when Discount was first sealed. It already implements CustomDiscount; it still needs its rules and its amountOff.

  4. Challenge

    Evaluate discounts with exhaustive pattern matching

    Exhaustive switch pattern matching

    With Discount sealed, a switch expression 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 old instanceof chain did. Record deconstruction patterns let a case pull a discount's fields straight out of the pattern, as in case PercentageDiscount(var rate) ->, with no manual accessor calls. src/main/java/lab/DiscountEvaluator.java needs its evaluate method built this way. ### Folding a list of cases into one result

    A single evaluate call 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 reuses evaluate for every entry without needing a second switch. totalDiscount, right below evaluate in the same file, needs that fold. ### Wiring the discount total into the order

    Order.computeTotal() from Step 2 gives you the subtotal; DiscountEvaluator.totalDiscount() now gives you the combined discount for that subtotal. finalTotal() in src/main/java/lab/Order.java just needs to combine the two, which is the moment the sealed-and-switched discount hierarchy actually changes what a customer pays.

  5. Challenge

    Wire payments and nested types into the finished order

    Enums that carry data and behavior

    An enum constant 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 an EnumMap keyed 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.java declares CREDIT_CARD, DEBIT_CARD, PAYPAL, and BANK_TRANSFER and an empty SURCHARGE_RATES map; the constants need their rates, the map needs filling once, and surchargeFor needs to read it. ### Static nested classes vs inner classes

    Java 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 Order at the end, with no shared mutable field like the old static-method builder had. src/main/java/lab/Order.java declares Builder as exactly that; its build() method still needs to assemble the Order it promises. ### Inner classes read the enclosing instance's live state

    An 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.ReceiptPrinter is declared as a non-static inner class for that reason: it can call computeTotal(), finalTotal(), and read paymentMethod straight off the enclosing Order without you passing anything in. printReceipt() still needs to turn that state into the receipt text.

  6. 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.sh
    

    src/main/java/lab/Main.java builds one order: two silk scarves at 45.00, a pair of gloves at 30.00, a 10% PercentageDiscount, a 5% LoyaltyDiscount, and PAYPAL as 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 Builder from Task 5.2 assembled the order, and your ReceiptPrinter from 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 from LoyaltyDiscount, which reached the same switch through the CustomDiscount case without ever being listed in Discount's permits clause. The 3.06 surcharge is PayPal's 3% of the discounted 102.00, read from the EnumMap you filled in Task 5.1. The currency went in as "usd" and comes out as USD because your compact constructor normalized it. ### 2. Watch bad values get refused

    The 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 old Money would have quietly held -5.00, and the old OrderLine would have shown the caller's clearance tag because it handed out the caller's own list. Now your compact constructors (Tasks 2.1, 2.2 and 3.2) and build() (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 says Accepted, that rule is missing. ### 3. Let the compiler catch a missing case

    The old instanceof chain returned zero discount for any type nobody remembered to handle. To see why your switch can't do that, open src/main/java/lab/DiscountEvaluator.java and delete this line from evaluate:

    case CustomDiscount cd -> cd.amountOff(subtotal);
    

    Rerun the bash runApp.sh command. This time the program doesn't build, and Maven points at your switch line (the line and column numbers depend on your file):

    [ERROR] .../DiscountEvaluator.java:[20,16] the switch expression does not cover all possible input values
    

    You sealed Discount in Task 3.1 and left out a default branch in Task 4.1, so the compiler knows every case that exists and rejects a switch that skips one. Put the line back and bash runApp.sh prints 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

Jeff Hopper is a polyglot solution developer with over 20 years of experience across several business domains. He has enjoyed many of those years focusing on the .Net stack.

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.

Get started with Pluralsight