Search⌘ K
AI Features

How much Refactoring?

Explore how to balance refactoring unit tests for clarity and maintainability with potential performance trade-offs in Java applications using JUnit. Understand extracting logic into helper methods to create precise, testable units and learn when to prioritize clean design over premature optimization to maintain flexibility and reduce complexity.

Too much refactoring could lead to some other unforeseen implications. Let’s look at these implications with the help of an example.

Extract the code that calculates the total weighting of all matches:

Java
public boolean matches(Criteria criteria) {
calculateScore(criteria);
boolean kill = false;
for (Criterion criterion: criteria) {
boolean match = criterion.matches(answerMatching(criterion));
if (!match && criterion.getWeight() == Weight.MustMatch) {
kill = true;
}
}
if (kill)
return false;
return anyMatches(criteria);
}
private void calculateScore(Criteria criteria) {
score = 0;
for (Criterion criterion: criteria)
if (criterion.matches(answerMatching(criterion)))
score += criterion.getWeight().getValue();
}

It might seem like we’re headed toward trouble.

Extract the logic that determines whether or not there are any must-meet criteria that aren’t a match: ...

Java
public boolean matches(Criteria criteria) {
calculateScore(criteria);
if (doesNotMeetAnyMustMatchCriterion(criteria))
return false;
return anyMatches(criteria);
}
private boolean doesNotMeetAnyMustMatchCriterion(Criteria criteria) {
for (Criterion criterion: criteria) {
boolean match = criterion.matches(answerMatching(criterion));
if (!match && criterion.getWeight() == Weight.MustMatch)
return true;
}
return false;
}

Shoot! We have ...