我有以下类和两个构造函数:
public Book(String bookTitle,ConcurrentHashMap<Integer,String> authors, String bookType ) throws InvalidDataException{
this.setBookTitle(bookTitle);
this.setAuthors(authors);
this.setType(bookType);
}
public Book(String bookTitle,ConcurrentHashMap<Integer,String> authors, String bookType, String bookStyle, String ISBN, int numberofPages) throws InvalidDataException{
this (bookTitle,authors,bookType);
this.fullConstructor = true;
this.setStyle(bookStyle);
this.setISBN(ISBN);
this.setNumberofPages(numberofPages);
}
我还有以下变量:
private Boolean fullConstructor= false;
检查调用了哪个构造函数。
我这样做是为了能够正确格式化toString()
方法:
@Override
public String toString() {
String viewOutput="";
if (!this.fullConstructor)
{
viewOutput="Book: " + this.getBookTitle() + " " + " Author(s): " + this.loopAuthors() + " Genre: " + this.bookType;
}
else{
viewOutput="Book: " + this.getBookTitle() + " " + " Author(s): " + this.loopAuthors() + " Genre: " + this.bookType + " Book Style: " + this.getBookStyle() + " ISBN-10: " + this.getISBN() + " Number of Pages: " + this.getNumberofPages() + " Book Style: " +this.getBookStyle() + " ISBN: " + this.getISBN() + "Number of Pages: " + this.getNumberofPages();
}
return viewOutput;
}
说明:
如果调用完整构造函数,则将私有变量fullConstructor设置为true。 toString知道如何根据fullConstructor值格式化返回值。我是这样做的,因为我必须再次检查以查看哪些变量是空的,这是设置者已经做过的,它似乎是重复的。
我在糟糕的练习中做了什么?如果是这样,我如何正确检查值是否为空,以便我可以正确创建返回字符串?
答案 0 :(得分:0)
我可能会用这个:
public Book(String bookTitle, Map<Integer, String> authors, String bookType, String bookStyle, String isbn, int numberOfPages) throws InvalidDataException {
setBookTitle(bookTitle);
setAuthors(authors);
setType(bookType);
setStyle(bookStyle);
setISBN(isbn);
setNumberOfPages(numberOfPages);
}
public Book(String bookTitle, Map<Integer, String> authors, String bookType) throws InvalidDataException {
this(bookTitle, authors, bookType, null, null, null);
}
@Override
public String toString() {
String result = String.format("Book: %s Author(s): %s Genre: %s",
getBookTitle(), loopAuthors(), bookType);
if (getBookStyle() == null && getISBN() == null && getNumberOfPages() == null)
return result;
return String.format("%s Book Style: %s ISBN-10: %s Number of Pages: %s",
result, getBookStyle(), getISBN(), getNumberOfPages());
}
这样,你就不需要一个完全构建的&#34; flag(看到附加字段有setter,稍后可以调用);这些字段只在toString
时间检查。此外,我冒昧地改变了您的toString
方法以使用String.format
,并且重复性更低。