#518 Code Review of Ball Type Detection Service

Companies:
Sberbank
Themes:
SpringSpring CoreCode Review

There is a service that determines a ball type by ball ID.

It is known that:

  • The called BallPropertiesService returns a property list (List<BallProperty>) for one ball. The list size ranges from 0 to 2^30;
  • BallProperty.code values from 0 through 9 describe ball size, where 0 is microscopic and 9 is gigantic;
  • BallProperty.code values from 100 through 129 describe the ball material;
  • BallProperty.code values 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 5 and 102, 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?

Java
@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

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in