Professional Practice: Immutability, Optional and Packaging a Program
Learn habits that professional Java developers rely on: immutable objects, defensive copies, safe use of Optional, hash-key pitfalls and packaging a program into a jar, with real runs of each.
In this lesson you will
- Design immutable classes
- Avoid null with Optional
- Avoid the mutable key bug
- Package code into a jar
About 28 minutes
The booking that changed by itself
A bug report reaches Hana: a booking printed on the invoice shows a different number of days than the one the customer agreed. Somewhere, code that was only supposed to look at the booking changed it. In a program with many classes, this kind of action at a distance is one of the most common sources of bugs. Professional Java code defends against it by making objects immutable wherever it can, by copying data at the boundaries, and by using types that make absence explicit.
An immutable object cannot change after it is created: all fields are final, there are no setters, and any mutable parts are copied on the way in and on the way out. Such objects are simple to reason about, safe to share between threads and safe to use as keys in a map. Optional is a container that either holds a value or is empty, returned by methods that may have no answer, so that callers cannot forget to handle the empty case the way they forget a null check. A classic pitfall is using a mutable object as a key in a HashMap or HashSet: if the fields that feed hashCode change after the object is stored, the object is lost inside the collection.
| Habit | Why |
|---|---|
| final fields, no setters | The object cannot change behind your back |
| Copy mutable inputs and outputs | Callers cannot reach inside |
| Return Optional, not null | Absence is visible in the type |
| Use immutable keys | Hash collections keep working |
| Small packages, one class per file | Code is findable and reusable |
import java.util.*;
final class Trip {
private final String bike;
private final List<Integer> days;
Trip(String bike, List<Integer> days) { this.bike = bike; this.days = List.copyOf(days); }
String bike() { return bike; }
List<Integer> days() { return days; }
}
class MutableKey {
String name;
MutableKey(String name) { this.name = name; }
@Override public boolean equals(Object o) { return o instanceof MutableKey k && k.name.equals(name); }
@Override public int hashCode() { return name.hashCode(); }
}
public class Main {
static Optional<Integer> findPrice(Map<String, Integer> prices, String bike) { return Optional.ofNullable(prices.get(bike)); }
public static void main(String[] args) {
List<Integer> original = new ArrayList<>(List.of(1, 2, 3));
Trip t = new Trip("City 1", original);
original.add(99);
System.out.println("caller changed its list, trip still has: " + t.days());
try { t.days().add(5); } catch (UnsupportedOperationException e) { System.out.println("outside code cannot change the trip: UnsupportedOperationException"); }
Map<String, Integer> prices = Map.of("City 1", 1200, "Tandem 3", 2400);
System.out.println("City 1: " + findPrice(prices, "City 1").map(p -> p + " cents").orElse("unknown"));
System.out.println("Moped 9: " + findPrice(prices, "Moped 9").map(p -> p + " cents").orElse("unknown"));
Set<MutableKey> set = new HashSet<>();
MutableKey key = new MutableKey("alpha");
set.add(key);
System.out.println("contains before change: " + set.contains(key));
key.name = "beta";
System.out.println("contains after changing the key: " + set.contains(key) + ", but the set still holds " + set.size() + " element");
}
}
caller changed its list, trip still has: [1, 2, 3]
outside code cannot change the trip: UnsupportedOperationException
City 1: 1200 cents
Moped 9: unknown
contains before change: true
contains after changing the key: false, but the set still holds 1 element
The caller added 99 to its own list after creating the trip, but the trip still has [1, 2, 3], because the constructor made a private copy with List.copyOf, and the copy is itself unmodifiable: code outside the class that tries to add a day gets an UnsupportedOperationException. The trip can therefore never change after construction. The Optional made absence a normal value: City 1 gave its price, and the unknown bike gave “unknown” through orElse, with no null check and no chance of a NullPointerException.
The last experiment is the mutable key bug. The key object was found in the set before its name changed, and after the name changed the set could no longer find it, although it still contained one element. The set had filed the object in a slot chosen from the old hash code, and the lookup now computes a different hash and looks in a different slot. The object is effectively lost. Immutable keys, such as strings, records and the Trip above, make this impossible.
Packaging a program into a jar
Professional code lives in packages, folders that group related classes, and ships as a jar file, a zip of class files with a manifest that names the main class. The program below does it for a tiny two-class package with the standard tools: javac with -d puts the class files in a folder tree that mirrors the package name, jar cfe creates a jar with an entry point, and java -jar runs it. Real projects use a build tool such as Maven or Gradle to do these steps and to manage dependencies, and the commands are the ones those tools run for you.
package shop.rental;
public class Price {
public static int days(int n) { return n * 1200; }
}
package shop.rental;
public class App {
public static void main(String[] a) { System.out.println("3 days cost " + Price.days(3)); }
}
$ javac -d out src/shop/rental/*.java
$ jar cfe app.jar shop.rental.App -C out .
$ jar tf app.jar
META-INF/
META-INF/MANIFEST.MF
shop/
shop/rental/
shop/rental/App.class
shop/rental/Price.class
$ java -jar app.jar
3 days cost 3600
The build produced a jar with these entries: META-INF/, META-INF/MANIFEST.MF, shop/, shop/rental/, shop/rental/App.class, shop/rental/Price.class. Running it printed “3 days cost 3600”. The class files sit in a folder tree, shop/rental, that mirrors the package name, which is why a class declared in package shop.rental must live in a directory of that path. The manifest in META-INF names shop.rental.App as the entry point, so java -jar knows where to start.
Check by hand: 3 x 1200 = 3600, the number the jar program printed, and the jar contains the two class files plus the manifest.
Copy mutable arguments when you store them and mutable fields when you return them, or return unmodifiable views. Otherwise the caller can reach inside.
Do not use Optional for fields or parameters. Its purpose is to make a method that may have no answer honest about it.
Every program in this lesson was compiled and run with OpenJDK 21 while the course was written. Java releases twice a year, so check the official Java documentation for the current version and for features added after Java 21.
Practice
Make a Customer class immutable with a record and copy a list of bookings defensively. Write a method that returns Optional for the longest booking. Then build your own two-class package into a jar and run it.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What makes a class immutable?
- Many methods
- A long name
- Final fields and no way to change them after creation
- Static fields only
Copy mutable parts.
Why copy a list in the constructor?
- To save memory
- So the caller cannot change it later
- To sort it
- To print it
List.copyOf makes an unmodifiable copy.
What does Optional represent?
- A faster int
- A value that may be absent
- A file
- A thread
It makes absence explicit.
Why did the set lose the object?
- Its hash code changed after it was stored
- The set was full
- The object was null
- Sets cannot hold objects
Never mutate fields used in hashCode while stored.
What does jar cfe define?
- A jar with an entry point class
- A new language
- A database
- A network
java -jar starts there.
Summary
- Immutable objects with defensive copies prevent action at a distance.
- Optional makes a missing result explicit.
- Do not mutate keys stored in hash collections.
- Packages and jars are how Java code is organised and shipped.
Questions
Should every class be immutable?
No, but make the ones that carry data immutable, and keep mutation in a few well-defined places.
What is Maven or Gradle?
Build tools that compile, test, package and manage dependencies. Check their documentation to start a project.
What is a module in Java?
A larger unit than a package, introduced in Java 9, with explicit dependencies. Most small programs do not need it.
