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?
You make a class for each thing in the domain that has a name, a set of rules, or a life of its own. And you leave the plain collections of fields as plain collections.
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.0));
catalogue.lend("Effective Java");
System.out.println(catalogue.availableTitles());
}
}
And here is how the classes fit together.
public class Book {
private final String title;
private final double price;
private boolean onLoan;
public Book(String title, double price) {
this.title = title;
this.price = price;
}
public String title() {
return title;
}
public void markOnLoan() {
onLoan = true;
}
public void markReturned() {
onLoan = false;
}
public boolean isOnLoan() {
return onLoan;
}
}
And the rule about where to draw the line comes down to one question. Does the thing have a rule that belongs to it? A Book has a rule about being on loan or not, and that rule is about the book and about nothing else. So it belongs in the Book class.
the thing its own class? why
---------------------- ---------------- ---------------------------
a book yes it has a loan state
a member yes it has a borrowing limit
the catalogue yes it has the lending rules
a list of loan dates no it is just a list of values
a string for a title no it is just text
And there is a second test that is worth using. Would you ever want to say something about this thing on its own? If you would write a sentence like "this book is currently on loan" then the loan state belongs on the Book. If the only sentences you would write are about the whole collection then it is just a field somewhere.
And there is a third test, and it is the one that saves you from making too many classes. Does the thing need a name in the code that is not just a label? If a value is only ever read and passed on and never has a rule, then a simple class with a couple of fields, or even a record, is enough.
// A small value object. It has a name but no rules of its own.
public record LoanDate(java.time.LocalDate date, java.time.LocalDate returnedOn) {
}
So the rule to remember is this. Give a thing its own class when it has a rule, a state, or a name you would use in a sentence about it.
The last question in this topic is about deciding which things deserve a class.