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

718 Views Asked by At

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?

4

There are 4 best solutions below

0
On BEST ANSWER

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())) {
0
On

Assume we have two class:

@Data
class X {
    private String field1;
}

@Data
class Y {
    private String field2;
}

define static method

static <F, T>void copy(F f, T t, Function<F, String> get, BiConsumer<T, String> set){
    String value = get.apply(f);
    if(value != null && value.isEmpty()){
        set.accept(t, value);
    }

}

and use it in your code:

    X x = new X();
    Y y = new Y();

    copy(x, y, X::getField1, Y::setField2);
1
On

You can implement this checking logic inside getter methods, i.e

public Optional<String> getChannelType() {

    if (channelType.isEmpty() || channelType == null)
        return Optional.empty();
    else
        return Optional.of(channelType);

}
0
On

If it's just copying between 2 beans with same variable names, then you can use BeanUtils.copyProperties to do so. Here we can say the BeanUtil to copy non null values. So the code will be reduced to 1 lines.

BeanUtils.copyProperties(source, destination, (.. optional parameter to copy non null value)