#518 Code Review of Ball Type Detection Service
There is a service that determines a ball type by ball ID.
It is known that:
-
The called
BallPropertiesServicereturns a property list (List<BallProperty>) for one ball. The list size ranges from0to2^30; -
BallProperty.codevalues from0through9describe ball size, where0is microscopic and9is gigantic; -
BallProperty.codevalues from100through129describe the ball material; -
BallProperty.codevalues in other ranges exist but have no business value in this case.
If the list contains:
-
a property with code
7, the ball is considered a basketball; -
a property with code
6, the ball is considered a football; -
a property with code
5, the ball is considered a tennis ball; -
properties with codes
5and102, the ball is considered a cannonball; - none of the above, the ball is considered a ping-pong ball.
It is guaranteed that if the list contains a BallProperty with a code from a range, it cannot contain another code from the same range, for example codes 1 and 2 cannot appear together.
What is wrong with this code?
@Service
@RequiredArgsConstructor
public class BallTypeService {
private final BallPropertiesService ballPropertiesService;
public BallType getType(Long ballId) {
List<BallProperty> ballProperties = ballPropertiesService.getBallProperties(ballId);
ballProperties.sort(Comparator.comparing(BallProperty::getCode).reversed());
return resolveType(ballProperties);
}
private BallType resolveType(List<BallProperty> ballProperties) {
long propertyNum = ballProperties.get(0).getCode();
long propertyNext = ballProperties.get(1).getCode();
if (propertyNum == 102 && propertyNext == 5) {
return BallType.CANNON_BALL;
}
if (propertyNum == 7) {
return BallType.BASKET_BALL;
}
if (propertyNum == 6) {
return BallType.FOOT_BALL;
}
if (propertyNum == 5) {
return BallType.TENNIS_BALL;
}
return BallType.PING_PONG_BALL;
}
}
public enum BallType {
BASKET_BALL,
FOOT_BALL,
CANNON_BALL,
TENNIS_BALL,
PING_PONG_BALL;
}
// library code
@Data
public class BallProperty {
private Integer group;
private Integer code;
private String description;
}
public interface BallPropertiesService {
List<BallProperty> getBallProperties(Long itemId);
}Question review
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor