3 回答

TA貢獻1796條經驗 獲得超10個贊
這個問題可能有很多很好的答案,根據您的具體用例,請記住設計模式(有時反模式是合理的)、最佳實踐等,這將使您的代碼更好。
也就是說,Question應該有添加新標簽的方法,因為它是具有tags屬性的類(不是嗎?)。您實施它的方式取決于您。它可能是這樣的:
public class Question {
// ...
public void addTags(Set<Tag> questionTagSet) {
this.tags.addAll(questionTagSet);
//...
}
}
這樣,無論您有一個類型的對象,Question您都可以添加這樣的標簽:
//...
Set<Tag> tags = new HashSet<>();
Question q = new Question();
q.addTags(tags);
//...
從這一點來看,我認為沒有“最佳”選擇,而是“適合您的用例的最佳選擇”。因此,一種選擇是重載(有關詳細說明,請參閱下面的方法重載),另一種選擇是新方法(當然具有不同的簽名)。
方法重載:一種方法接收所有參數,另一種方法接收所有參數,但是questionTagSet,在該方法中,您只能通過提供默認值來調用接收所有參數的方法:null?,F在,在接收questionTagSet參數的Question#addTags方法中,如果questionTagSet參數不是 ,您將調用該方法null。這將允許您使用相同的方法簽名,但具有來自控制器的不同參數。因此,您不必檢查每個控制器(可能很多),因為您只將檢查移動到一個地方:createQuestionWithTags方法。
像這樣的東西:
帶有所有參數的方法,但 questionTagSet
public Question createQuestionWithTags(String text, Project project, User createdUser, Date createdDate) {
return createQuestionWithTags(text, project, createdUser, createdDate, null);
}
帶有所有參數的方法
public Question createQuestionWithTags(String text, Project project, User createdUser, Date createdDate,Set<Tag> questionTagSet) {
Question q = new Question();
//... some more additional logic here
if (questionTagSet != null) { //<- logic for adding tags moved here
q.addTags(questionTagSet);
}
return q;
}
如果您想對questionTagSet參數進行一些檢查,則此實現可能會有所不同。
這樣做的優點:
您可以
createQuestionWithTags
以不同的方式從不同的控制器調用該方法,而無需擔心questionTagSet
參數:utility.createQuestionWithTags("", new Project(), new User(), new Date(), new HashSet<Tag>())
utility.createQuestionWithTags("", new Project(), new User(), new Date(), null)
utility.createQuestionWithTags("", new Project(), new User(), new Date())
缺點
重載有時會很棘手且令人困惑
在進行單元測試時,您需要確定正在測試哪種方法,因為簽名幾乎相同。
添加回答
舉報