我正在研究getters/setters
,一般的想法是它们是邪恶的,应该避免。您应该让对象完成工作并产生结果。
阅读材料:
为什么 getter 和 setter 方法是邪恶的 https://www.javaworld.com/article/2073723/core-java/why-getter-and-setter-methods-are-evil.html
为什么要使用 getter 和 setter? https://stackoverflow.com/questions/1568091/why-use-getters-and-setters?rq=1
考虑到所有这些,假设我有一本书class
看起来像这样:
publc final Book{
private final String title;
private final List<Authors> listofAuthors;
private final int numberofpages;
//constructor not included in example.
//getters for title, listofAuthors, and numberofpages
public int numberofpagesleft(int pagesRead){
//code to determine number of pages left
}
public boolean isWrittenBy(Author author){
//code to determine if book contains author
}
}
如果我有一个UI
(ex. JavaFX
, webpage
等..)并希望我的课程灵活,包括getters
for title
, listofAuthors
and numberofpages
用于显示目的encapsulation
?
Example:
//library is an List<Book> collection, and author is an object of the Author class.
for (Book book : library){
if(book.isWrittenBy(author){
System.out.println("Books in your collection written by " + author.toString() + " include:" );
System.out.println(book.getTitle());
}
}
or
for (Book book : library){
//returns a Collections.unmodifiableList().
if(book.getAuthors(){
//code to build a set of authors in my library
}
}
问题:
正在呼叫getTitle()
or getAuthors()
在循环中断中encapsulation
?
如果上述问题的答案是肯定的,那么我将如何展示这本书isWrittenBy()
回报true
?以及我如何收集图书馆中的所有作者?