Search code examples
javaspringspring-bootisnullorempty

avoid everytime check for nonnull and nonempty variables at dto in spring


I have following method which updates user data if the data is nonEmpty or nonNull

public Users updateUser(Users requestBody) throws AppServiceException {

        Users user = new Users();
        try {

            user = userDAO.getUserByUserId(requestBody.getUserId());

        if (requestBody.getRole() != null && !requestBody.getRole().isEmpty()) {
            user.setRole(requestBody.getRole());
        }

        if (requestBody.getUserName() != null && !requestBody.getUserName().isEmpty()) {
            user.setUserName(requestBody.getUserName());
        }

        if (requestBody.getChannelType() != null && !requestBody.getChannelType().isEmpty()) {
            user.setChannelType(requestBody.getChannelType());
        }

        if (requestBody.getStatus() != null && !requestBody.getStatus().isEmpty()) {
            user.setStatus(requestBody.getStatus());
        }
        if (requestBody.getDevice() != null) {
            user.setDevice(requestBody.getDevice());
        }

        user.setUpdatedDate(new Date());

        user = userDAO.updateUser(user);


        } catch (Exception e) {

            e.printStackTrace();
            throw new AppServiceException(AppServiceException._FAIL_TO_UPDATE);
        }
        return user;
    }

I checked the values for nonNull & isEmpty everytime.

How can I avoid this?


Solution

  • You can use Apache commons lang's StringUtils.isEmpty(java.lang.String)

    Checks if a String is empty ("") or null.

    If your code:

    if (StringUtils.isEmpty(requestBody.getStatus())) {