java - 如何清理重复的 if 语句

标签 java coding-style

我目前投入了大量时间来清理我的代码。 我有很多 If 语句来处理前端的注册表单。

读完《干净的代码》这本书后我有这样的感觉。这只是丑陋的,但是我似乎没有为下面的代码找到任何“惊人/令人难以置信”的清理格式。

假设我还有 15 个 if 语句,那么这将导致大量重复,那么是否有可能进行重大改进?

User userByUsername = userRepo.findByUsername(user.getUsername());
User userByEmail = userRepo.findUserByEmail(user.getEmail());
if (userByUsername != null && userByEmail != null) {
    throw new AccountException("Email and username already exist");
}
if (userByUsername != null) {
    throw new AccountException("Username already exist");
}
if (userByEmail != null) {
    throw new AccountException("Email already exist");
}

使用另一种方法的另一个示例:

public void addConditions(ReservationDto reservationDto) {
    long roomId = roomService.findRoomByRoomName(reservationDto.getRoomName()).getRoomId();
    // Check for adding room: Roomcapacity for timeslote reached
    // If maxCapacityAfternoon reached, then only add to afternoon possible
    int roomCapacity = roomService.findRoomByRoomId(roomId).getCapacity();
    boolean maxCapacityMorning = roomCapacity <= getNumberOfReservationsForRoomByDateVoormiddag(roomId, reservationDto.getDate());
    boolean maxCapacityAfternoon = roomCapacity <= getNumberOfReservationsForRoomByDateNamiddag(roomId, reservationDto.getDate());
    boolean isMorning = reservationDto.isMorning();
    boolean isAfternoon = reservationDto.isAfternoon();
    capacityConditions(reservationDto, maxCapacityMorning, maxCapacityAfternoon);
    // Check: Reservation can only be made when it meets the following conditions
    // - Same user
    // - is active
    // - Morning and date overlap
    // - Afternoon and date overlap
    Reservation mappedReservation = mapReservationDto(reservationDto);
    int amountOfReservationsForDay = reservationRepo.existsReservationForDay(mappedReservation.getUsername(), mappedReservation.getDate());
    if (isMorning && isAfternoon) {
        if (amountOfReservationsForDay > 0) {
            throw new ServiceException(RESERVATION_MSG + FOR_FULL_DAY + reservationDto.getDate());
        }
        if (reservationRepo.existsReservationForMorning(mappedReservation.getUsername(), mappedReservation.getDate()) > 0
                || reservationRepo.existsReservationForAfterNoon(mappedReservation.getUsername(), mappedReservation.getDate()) > 0
        ) {
            throw new ServiceException(RESERVATION_MSG + "in de voor- of namiddag.");
        }
    }
    if (isMorning && !isAfternoon) {
        if (amountOfReservationsForDay > 0) {
            throw new ServiceException(RESERVATION_MSG + FOR_FULL_DAY + reservationDto.getDate());
        }
        if (reservationRepo.existsReservationForMorning(mappedReservation.getUsername(), mappedReservation.getDate()) > 0) {
            throw new ServiceException(RESERVATION_MSG + "in de voormiddag.");
        }
    }
    if (!isMorning && isAfternoon) {
        if (amountOfReservationsForDay > 0) {
            throw new ServiceException(RESERVATION_MSG + FOR_FULL_DAY + reservationDto.getDate());
        }
        if (reservationRepo.existsReservationForAfterNoon(mappedReservation.getUsername(), mappedReservation.getDate()) > 0) {
            throw new ServiceException(RESERVATION_MSG + "in de namiddag");
        }
    }
    if (!isMorning && !isAfternoon) {
        throw new ServiceException("Selecteer een tijdstip voor uw reservatie");
    }
}

正如你所看到的,当我想要添加预订时,我的项目有很多条件。这些只是附加条件,并未考虑房间容量检查。这也是一长串“如果”

最佳答案

您可以为所有可能抛出的数据验证异常创建一个枚举

public enum DataValidationError {
    USERNAME_EXISTS,
    EMAIL_EXISTS,
    ...
}

public static class AccountException extends Exception {
    private final List<DataValidationError> errors;

    public AccountException(List<DataValidationError> errors) {
        this.errors = errors;
    }

    public List<DataValidationError> getErrors() {
        return errors;
    }
}

Usage:

List<DataValidationError> errors = new ArrayList<>();

User userByUsername = userRepo.findByUsername(user.getUsername());
User userByEmail = userRepo.findUserByEmail(user.getEmail());

if (userByUsername != null) {
    errors.add(DataValidationError.USERNAME_EXISTS);
}
if (userByEmail != null) {
    errors.add(DataValidationError.EMAIL_EXISTS);
}
if (!errors.isEmpty()) {
    throw new AccountException(errors);
}

这样,您就可以在枚举中添加尽可能多的错误,并不断将它们添加到列表中,并在最后仅抛出一次。

关于java - 如何清理重复的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74861816/

相关文章:

java - 假设 i=0 并且数组的所有元素都初始化为 0 a[i++] = a[i++] + 2;

java - 我可以让 Tomcat 7 部署已配置的 Web 应用程序但不启动它们吗?

c++ - Eclipse:如何格式化指针声明

xml - 使用父 XML 元素作为重复出现的子元素的容器?

javascript - 使用 jquery 的 javascript 中的可访问性和代码组织问题

coding-style - 我应该在快速原型(prototype)制作时关注代码质量吗?

java - 构建依赖于其他库的 Java 库

java - 使用 org.zalando.logbook 打印带有 multipart/form-data 的请求

java - 多线程Java服务器: allowing one thread to access another one

java - 为什么 split (".") 会失败? java