Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

What is the best way to change external variable with Optional? #96

Answered by tboychuk
aquariusmaster asked this question in Q&A
Discussion options

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");
 }
 }
You must be logged in to vote

Replies: 1 comment

Comment options

@aquariusmaster the first option is fine.

You must be logged in to vote
0 replies
Answer selected by aquariusmaster
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /