March 2018
Intermediate to advanced
208 pages
4h 52m
English
| | class Inventory { |
| | |
| | private final List<Supply> supplies; |
| | |
| | Inventory(List<Supply> supplies) { |
| » | this.supplies = supplies; |
| | } |
| | |
| | List<Supply> getSupplies() { |
| » | return supplies; |
| | } |
| | } |
Practically any nontrivial object has some inner state that’s accessible from the outside. You need to be careful how you make this state available. Otherwise, you risk serious bugs.
The Inventory here shows a fairly common example of a class that maintains a data structure. That data structure is initialized externally and inserted into the constructor of the Inventory. Nothing’s obviously wrong with the class itself, but let’s look at the usage:
| | List<Supply> externalSupplies = new ArrayList<>(); |
| | Inventory inventory = ... |