-
-
Notifications
You must be signed in to change notification settings - Fork 501
What is the best way to change external variable with Optional? #96
Answered
by
tboychuk
aquariusmaster
asked this question in
Q&A
-
I need to change some external variable in case of optional is present. What is the best way to do that with Optional.
Code example:
private void checkCORS(HttpRequest request, HttpResponse response) {
Optional.ofNullable(request.getHeaders().get("Origin"))
.map(list -> list.get(0))
.filter(HealthHttp::isWhitelisted)
.ifPresent(origin -> {
response.appendHeader("Access-Control-Allow-Origin", origin);
response.appendHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
});
}
As far as I know it is not recommended to change external variable inside lambda. In my case the external variable is HttpResponse response.
Please advice should I change the above code to:
private void checkCORS(HttpRequest request, HttpResponse response) {
Optional<String> originValueOptional = Optional.ofNullable(request.getHeaders().get("Origin"))
.map(list -> list.get(0))
.filter(HealthHttp::isWhitelisted);
if (originValueOptional.isPresent()) {
response.appendHeader("Access-Control-Allow-Origin", originValueOptional.get());
response.appendHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
}
}
Beta Was this translation helpful? Give feedback.
All reactions
Answered by
tboychuk
Jul 26, 2021
@aquariusmaster the first option is fine.
Replies: 1 comment
-
@aquariusmaster the first option is fine.
Beta Was this translation helpful? Give feedback.
All reactions
0 replies
Answer selected by
aquariusmaster
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment