Link to home
Start Free TrialLog in
Avatar of ltpitt
ltpitt

asked on

How to simplify this Java null check using Optional

I have this snippet in a project I am writing:
private <T> String toStringOrNull(T value) {
    return value == null ? null : value.toString();
}

Open in new window

And I really do not like it.

How can I make it more modern, secure and readable?

I think Optional is a good fit but I am not sure it would make sense to use something like:
Optional.of(value).orElse(null)

Open in new window

What I do is to retrieve entities from a database and those entities are then mapped to a DTO.
I copy the properties using:
BeanUtils.copyProperties(source, target);

Open in new window

But some of the properties can be null and I need to handle that.
Maybe I should make the DTO fields ignore null fields (like here: https://www.baeldung.com/jackson-ignore-null-fields)

What would be the best practice? 

Thanks for your help.
ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial