Search⌘ K

Other Design Thoughts

Explore key design principles like SOLID and command-query separation to enhance Java code quality. Understand lazy initialization to optimize performance and learn how the Visitor pattern helps maintain clean, extensible code. This lesson guides you in refactoring design to simplify testing and reduce duplicated logic.

We'll cover the following...

The MatchSet() constructor does the work of calculating the score. If the calculated score isn’t consumed by a client, the effort to compute it is a waste. For this reason, avoid doing any real work in constructors.

Change the code to calculate the score when it’s requested:

Java
public class MatchSet {
// ...
private Map<String, Answer> answers;
private Criteria criteria;
public MatchSet(Map<String, Answer> answers, Criteria criteria) {
this.answers = answers;
this.criteria = criteria;
}
public int getScore() {
int score = 0;
for (Criterion criterion: criteria)
if (criterion.matches(answerMatching(criterion)))
score += criterion.getWeight().getValue();
return score;
}
//...
}

Lazy initialization

The score field goes away, and the calculateScore() method gets inlined into getScore(). If recalculating the score each time getScore() gets called is a ...