How do you model a real domain such as a library in classes, and where do you draw the line between a class and a plain set of fields?
Model the nouns that the business actually reasons about and give each one the behaviour that belongs to it alone. Here a Book owns its title and price, and a Catalogue owns the collection and the operations on that collection: adding, counting, valuing and finding. The catalogue is the object that knows what a library is for, and it does not leak its internal list to callers.
public class Main {
public static void main(String[] args) {
Catalogue catalogue = new Catalogue();
catalogue.add(new Book("Effective Java", 45.0));
catalogue.add(new Book("Clean Code", 38.5));
System.out.println(catalogue.count());
System.out.println(catalogue.totalValue());
System.out.println(catalogue.find("Clean Code"));
}
}
class Catalogue {
private final java.util.List<Book> books = new java.util.ArrayList<>();
void add(Book book) { books.add(book); }
int count() { return books.size(); }
double totalValue() {
double sum = 0;
for (Book b : books) { sum += b.price(); }
return sum;
}
String find(String title) {
for (Book b : books) {
if (b.title().equals(title)) { return "found: " + b.title(); }
}
return "not found";
}
}
class Book {
private final String title;
private final double price;
Book(String title, double price) { this.title = title; this.price = price; }
String title() { return title; }
double price() { return price; }
}The output shows the split working: two books, a total value of 83.5, and a lookup that reports found: Clean Code. Each of those answers comes from a different object, and none of them required the caller to know how the catalogue is stored internally.
The line between a class and a plain set of fields is drawn by behaviour, not by shape. If a group of values is only ever passed around and printed, keep it as fields on the object that owns it. If it has rules, if it needs to be validated, or if it is referred to in several places in the language of the business, it deserves to be a class of its own. Book earns its place the moment price rules start to vary; a string field for the author might not.
The final check, and the one to mention in an interview, is whether the names match how the business talks. If your classes need a glossary to explain them, the model is probably not yet aligned with the domain.