Suppose, I have a class Book.
public class Book {
private Author author;
private int pageCount;
// ... getters and setters
}
And another class Author.
public class Author {
private String name;
private int age;
// ... getters and setters
}
Now, which one of the following is the best way to access the auther name of a book repeatedly from any other class?
void doSomethingA(Book book) {
print(book.getAuthor().getName());
publish(book.getAuthor().getName());
}
Or,
void doSomethingB(Book book) {
Author author = book.getAuthor();
print(author.getName());
publish(author.getName());
}
Or,
void doSomethingC(Book book) {
Author author = book.getAuthor();
String authorName = author.getName();
print(authorName);
publish(authorName);
}
We want to avoid bugs, by making the code easy to read, and removing duplication (because with duplication we may make a change in only opne place when it should have been made in several places)
So none of your options are best. The best is:
void doSomethingC(Book book) {
String authorName = book.getAuthor().getName();
print(authorName);
publish(authorName);
}
Now if we decide that we need to do something to the author name, we can change the code to:
void doSomethingC(Book book) {
String authorName = massageAuthor(book.getAuthor().getName());
print(authorName);
publish(authorName);
}
And the new value is used in both places.