2017-03-16 33 views
0

我有以下Book類(我省略了不相關的代碼)。在構造函數中檢查列表時的正確做法

public final class Book { 

    public Book(String bookTitle, List<Author> listofAuthors, int numberofchapters, String ISBN) 
    { 
     //Ommitted other variable initializations. 
     this.checkAuthors(listofAuthors); 
     this.listofAuthors = Collections.unmodifiableList(new ArrayList<Author>(listofAuthors));   
    } 

    private void checkAuthors(List<Author> checkifEmpty) 
    { 
     if(checkifEmpty == null){ 
     throw new IllegalArgumentException("List of authors is null"); 
     } 

     if (checkifEmpty.size() == 0){ 
      throw new IllegalArgumentException("The authors list contains no authors"); 
     } 

     for (Author checkEmpty : checkifEmpty){ 
      if(checkEmpty == null){ 
      throw new IllegalArgumentException("A book must have at least one author"); 
     } 
    } 

} 

我包括私有方法來檢查作者的List,以確保該List集合不爲0,並防止

Author bookAuthor = null; 

List<Author> listofAuthors = new ArrayList<Author>(); 
listofAuthors.add(bookAuthor); 

List<Author> listofAuthors = null; 
Book tlac = new Book("book title goes here", listofAuthors, 30, "isbn goes here"); 

的發生。

問題:

  1. 呼喚從constructor一個private方法和做的工作還有認爲是不好的做法?如果是這樣,我應該如何糾正它?

  2. private方法checkAuthors我使用== instead of equals()。我的目的是檢查存儲在List<Author>中的對象的值是否爲null。是這種情況下,我找到了使用==的作品,如果我使用equals()它給我null作爲錯誤信息。在這種情況下正確使用==,如果不是,我該怎麼做?

回答

0

呼喚從構造一個私有方法,做它做認爲是不好的實踐工作?如果是這樣,我應該如何糾正它?

不,只要它有道理,即減少單個方法或代碼的複雜性,

在私有方法checkAuthors中,我使用==而不是equals()。我的目的是檢查沒有存儲在列表中的對象的值爲null。是這種情況下,我發現使用==作品,如果我使用equals()它給我空作爲錯誤消息。在這種情況下使用==正確的,如果不是,我該怎麼做?

取決於對象的專業化程度。如果這是在應用程序中的多個地方使用的關鍵狀態檢查,那麼快速構建失敗是個好主意。考慮使用諸如Guava的preconditions之類的東西來節省一些打字的時間。

相關問題