Suppose that there is a method for searching for book authors by book identifier. What should be passed as a parameter for such a method - only book.id (int) or the entire book object?
I make the assumption that "book authors" are an attribute of the book. So I imagine something like the following class:
class Book { private int id; private List<Author> authors; // ... maybe some other book information public int getID() { return this.id } public void setID(int value) { this.id = value } public List<Author> getAuthors() { return this.authors.clone(); } // ... }
Given an instance of the Book ( aBook ) object to determine the list of authors, I would expect that I can call aBook.getAuthors() , which does not require any parameters.
I would refuse to create partially created domain objects. In other words, given bookid and searching for a list of authors, I would like the client code to look like this:
Book aBook = library.findBook(bookid); List<Author> authors = aBook.getAuthors();
and less:
Book bookQuery = new Book().setID(bookid); // partially instantiated Book Book aBook = library.findBook(bookQuery); List<Author> aBook = book.getAuthors();
The first version reduces the number of excluded objects created by client code. (In this case, bookQuery , which is not a real book.)
It also makes it easier to read code - and therefore its support. This is because bookQuery does not do what the maintenance programmer expects. For example, I expect that two books with the same identifier will have the same type, authors, ISBN, etc. These statements will fail for bookQuery and aBook .
Third, this minimizes the likelihood that you will ever pass an invalid (partially instance) Book object to a method that expects a real Book. This is a mistake in which a failure (in a method) can occur far from the cause (partial implementation).
Paul hanbury
source share