Is this example of use Optionals in java 8 correct? How would you rewrite it?












3














I've started to use Java's 8 Optionals. and I would like to share this method, it is "code smells" example and I would like to rewrite it using java 8 and optionlas and functional (declarative) style, so I am interested in seeing your opinion on it. Let's consider this method:



  public boolean isTokenValid(String userAgent, Optional<String> apiKey) {
LOGGER.info(String.format("userAgent : %s, Key ?: %s", userAgent, apiKey.isPresent()));
if ("ALFA".equalsIgnoreCase(userAgent)){
return (apiKey != null && apiKey.isPresent()
&& ispropertyExists(ALFA_TYPE, apiKey.get()));
}
else {
return (apiKey != null && apiKey.isPresent()
&& ispropertyExists(BETA_TYPE, apiKey.get()));
}
}


Where "ispropertyExists" returns boolean type, and "ALFA_TYPE" and "OMEGA_TYPE" are enums constants.
So below is the way I rewrote this method in intention to improve the readability and practice functional thinking style. I've added comments, to explain my thoughts and reasons I did so and so, I appreciate your opinions and examples of your ways if you think you able to improve it.



    /**
* We should not pass Optionals as a parameters to the methods. We
* should use Optionals only for return value when we are not sure if value will
* be presented at the end of the calculations or not.
*/
public boolean isTokenValid(String userAgent, String apiKey) {
LOGGER.info(String.format("userAgent : %s, Key ?: %s", userAgent, apiKey));

/**
* If apiKey is null then it is incorrect. And execution will stop after
* Optional.ofNullable(apiKey), since monad will be having null value. If apiKey
* is not null then we still want to filter out empty strings. If after filter
* there will be no value, then execution will stop.
* If we have some value for apiKey then it is ok and we map the monad to the
* userAgent value to proceed the chain of calls on monad.
*/
Optional<String> userAgentOptional = Optional.ofNullable(apiKey).filter(StringUtils::isNotBlank)
.map(ak -> userAgent);

/**
* We map "userAgent" value to boolean (if it is a alfa or not). Then
* we map that boolean to boolean value which represents security check in db
* itself.
*/
Optional<Boolean> isValid = userAgentOptional.map(ua -> "ALFA".equalsIgnoreCase(ua))
.map(isAlfa -> isAlfa ? ispropertyExists(ALFA_TYPE, apiKey)
: ispropertyExists(BETA_TYPE, apiKey));

/**
* And all in all we get value from our optional boolean. If "somehow" it is
* ended up to be empty, then we retrun "false", if it is not empty, then the
* value will itself be returned.
*/
return isValid.orElse(false);
}


Thank you.










share|improve this question




















  • 2




    couldn't you just combine those chain of maps into one and work along...besides optional as an argument is a bad practice in its own.
    – nullpointer
    Nov 11 '18 at 11:42










  • Ok, so your opinion is - everything is OK but just contract it to: "Optional.ofNullable(apiKey).filter(...) .map(...) .map(...) .map(...) .orElse(false);" is my understending correct?
    – Pavel
    Nov 11 '18 at 11:45


















3














I've started to use Java's 8 Optionals. and I would like to share this method, it is "code smells" example and I would like to rewrite it using java 8 and optionlas and functional (declarative) style, so I am interested in seeing your opinion on it. Let's consider this method:



  public boolean isTokenValid(String userAgent, Optional<String> apiKey) {
LOGGER.info(String.format("userAgent : %s, Key ?: %s", userAgent, apiKey.isPresent()));
if ("ALFA".equalsIgnoreCase(userAgent)){
return (apiKey != null && apiKey.isPresent()
&& ispropertyExists(ALFA_TYPE, apiKey.get()));
}
else {
return (apiKey != null && apiKey.isPresent()
&& ispropertyExists(BETA_TYPE, apiKey.get()));
}
}


Where "ispropertyExists" returns boolean type, and "ALFA_TYPE" and "OMEGA_TYPE" are enums constants.
So below is the way I rewrote this method in intention to improve the readability and practice functional thinking style. I've added comments, to explain my thoughts and reasons I did so and so, I appreciate your opinions and examples of your ways if you think you able to improve it.



    /**
* We should not pass Optionals as a parameters to the methods. We
* should use Optionals only for return value when we are not sure if value will
* be presented at the end of the calculations or not.
*/
public boolean isTokenValid(String userAgent, String apiKey) {
LOGGER.info(String.format("userAgent : %s, Key ?: %s", userAgent, apiKey));

/**
* If apiKey is null then it is incorrect. And execution will stop after
* Optional.ofNullable(apiKey), since monad will be having null value. If apiKey
* is not null then we still want to filter out empty strings. If after filter
* there will be no value, then execution will stop.
* If we have some value for apiKey then it is ok and we map the monad to the
* userAgent value to proceed the chain of calls on monad.
*/
Optional<String> userAgentOptional = Optional.ofNullable(apiKey).filter(StringUtils::isNotBlank)
.map(ak -> userAgent);

/**
* We map "userAgent" value to boolean (if it is a alfa or not). Then
* we map that boolean to boolean value which represents security check in db
* itself.
*/
Optional<Boolean> isValid = userAgentOptional.map(ua -> "ALFA".equalsIgnoreCase(ua))
.map(isAlfa -> isAlfa ? ispropertyExists(ALFA_TYPE, apiKey)
: ispropertyExists(BETA_TYPE, apiKey));

/**
* And all in all we get value from our optional boolean. If "somehow" it is
* ended up to be empty, then we retrun "false", if it is not empty, then the
* value will itself be returned.
*/
return isValid.orElse(false);
}


Thank you.










share|improve this question




















  • 2




    couldn't you just combine those chain of maps into one and work along...besides optional as an argument is a bad practice in its own.
    – nullpointer
    Nov 11 '18 at 11:42










  • Ok, so your opinion is - everything is OK but just contract it to: "Optional.ofNullable(apiKey).filter(...) .map(...) .map(...) .map(...) .orElse(false);" is my understending correct?
    – Pavel
    Nov 11 '18 at 11:45
















3












3








3


1





I've started to use Java's 8 Optionals. and I would like to share this method, it is "code smells" example and I would like to rewrite it using java 8 and optionlas and functional (declarative) style, so I am interested in seeing your opinion on it. Let's consider this method:



  public boolean isTokenValid(String userAgent, Optional<String> apiKey) {
LOGGER.info(String.format("userAgent : %s, Key ?: %s", userAgent, apiKey.isPresent()));
if ("ALFA".equalsIgnoreCase(userAgent)){
return (apiKey != null && apiKey.isPresent()
&& ispropertyExists(ALFA_TYPE, apiKey.get()));
}
else {
return (apiKey != null && apiKey.isPresent()
&& ispropertyExists(BETA_TYPE, apiKey.get()));
}
}


Where "ispropertyExists" returns boolean type, and "ALFA_TYPE" and "OMEGA_TYPE" are enums constants.
So below is the way I rewrote this method in intention to improve the readability and practice functional thinking style. I've added comments, to explain my thoughts and reasons I did so and so, I appreciate your opinions and examples of your ways if you think you able to improve it.



    /**
* We should not pass Optionals as a parameters to the methods. We
* should use Optionals only for return value when we are not sure if value will
* be presented at the end of the calculations or not.
*/
public boolean isTokenValid(String userAgent, String apiKey) {
LOGGER.info(String.format("userAgent : %s, Key ?: %s", userAgent, apiKey));

/**
* If apiKey is null then it is incorrect. And execution will stop after
* Optional.ofNullable(apiKey), since monad will be having null value. If apiKey
* is not null then we still want to filter out empty strings. If after filter
* there will be no value, then execution will stop.
* If we have some value for apiKey then it is ok and we map the monad to the
* userAgent value to proceed the chain of calls on monad.
*/
Optional<String> userAgentOptional = Optional.ofNullable(apiKey).filter(StringUtils::isNotBlank)
.map(ak -> userAgent);

/**
* We map "userAgent" value to boolean (if it is a alfa or not). Then
* we map that boolean to boolean value which represents security check in db
* itself.
*/
Optional<Boolean> isValid = userAgentOptional.map(ua -> "ALFA".equalsIgnoreCase(ua))
.map(isAlfa -> isAlfa ? ispropertyExists(ALFA_TYPE, apiKey)
: ispropertyExists(BETA_TYPE, apiKey));

/**
* And all in all we get value from our optional boolean. If "somehow" it is
* ended up to be empty, then we retrun "false", if it is not empty, then the
* value will itself be returned.
*/
return isValid.orElse(false);
}


Thank you.










share|improve this question















I've started to use Java's 8 Optionals. and I would like to share this method, it is "code smells" example and I would like to rewrite it using java 8 and optionlas and functional (declarative) style, so I am interested in seeing your opinion on it. Let's consider this method:



  public boolean isTokenValid(String userAgent, Optional<String> apiKey) {
LOGGER.info(String.format("userAgent : %s, Key ?: %s", userAgent, apiKey.isPresent()));
if ("ALFA".equalsIgnoreCase(userAgent)){
return (apiKey != null && apiKey.isPresent()
&& ispropertyExists(ALFA_TYPE, apiKey.get()));
}
else {
return (apiKey != null && apiKey.isPresent()
&& ispropertyExists(BETA_TYPE, apiKey.get()));
}
}


Where "ispropertyExists" returns boolean type, and "ALFA_TYPE" and "OMEGA_TYPE" are enums constants.
So below is the way I rewrote this method in intention to improve the readability and practice functional thinking style. I've added comments, to explain my thoughts and reasons I did so and so, I appreciate your opinions and examples of your ways if you think you able to improve it.



    /**
* We should not pass Optionals as a parameters to the methods. We
* should use Optionals only for return value when we are not sure if value will
* be presented at the end of the calculations or not.
*/
public boolean isTokenValid(String userAgent, String apiKey) {
LOGGER.info(String.format("userAgent : %s, Key ?: %s", userAgent, apiKey));

/**
* If apiKey is null then it is incorrect. And execution will stop after
* Optional.ofNullable(apiKey), since monad will be having null value. If apiKey
* is not null then we still want to filter out empty strings. If after filter
* there will be no value, then execution will stop.
* If we have some value for apiKey then it is ok and we map the monad to the
* userAgent value to proceed the chain of calls on monad.
*/
Optional<String> userAgentOptional = Optional.ofNullable(apiKey).filter(StringUtils::isNotBlank)
.map(ak -> userAgent);

/**
* We map "userAgent" value to boolean (if it is a alfa or not). Then
* we map that boolean to boolean value which represents security check in db
* itself.
*/
Optional<Boolean> isValid = userAgentOptional.map(ua -> "ALFA".equalsIgnoreCase(ua))
.map(isAlfa -> isAlfa ? ispropertyExists(ALFA_TYPE, apiKey)
: ispropertyExists(BETA_TYPE, apiKey));

/**
* And all in all we get value from our optional boolean. If "somehow" it is
* ended up to be empty, then we retrun "false", if it is not empty, then the
* value will itself be returned.
*/
return isValid.orElse(false);
}


Thank you.







java java-8 java-stream monads optional






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 5:31









ETO

1,722321




1,722321










asked Nov 11 '18 at 11:21









Pavel

426514




426514








  • 2




    couldn't you just combine those chain of maps into one and work along...besides optional as an argument is a bad practice in its own.
    – nullpointer
    Nov 11 '18 at 11:42










  • Ok, so your opinion is - everything is OK but just contract it to: "Optional.ofNullable(apiKey).filter(...) .map(...) .map(...) .map(...) .orElse(false);" is my understending correct?
    – Pavel
    Nov 11 '18 at 11:45
















  • 2




    couldn't you just combine those chain of maps into one and work along...besides optional as an argument is a bad practice in its own.
    – nullpointer
    Nov 11 '18 at 11:42










  • Ok, so your opinion is - everything is OK but just contract it to: "Optional.ofNullable(apiKey).filter(...) .map(...) .map(...) .map(...) .orElse(false);" is my understending correct?
    – Pavel
    Nov 11 '18 at 11:45










2




2




couldn't you just combine those chain of maps into one and work along...besides optional as an argument is a bad practice in its own.
– nullpointer
Nov 11 '18 at 11:42




couldn't you just combine those chain of maps into one and work along...besides optional as an argument is a bad practice in its own.
– nullpointer
Nov 11 '18 at 11:42












Ok, so your opinion is - everything is OK but just contract it to: "Optional.ofNullable(apiKey).filter(...) .map(...) .map(...) .map(...) .orElse(false);" is my understending correct?
– Pavel
Nov 11 '18 at 11:45






Ok, so your opinion is - everything is OK but just contract it to: "Optional.ofNullable(apiKey).filter(...) .map(...) .map(...) .map(...) .orElse(false);" is my understending correct?
– Pavel
Nov 11 '18 at 11:45














3 Answers
3






active

oldest

votes


















3














I would combine all the operations in one chained statement and return the result avoiding unnecessary Optional variables.



 return Optional.ofNullable(apiKey)
.filter(StringUtils::isNotBlank)
.map(ak -> userAgent)
.map("ALFA"::equalsIgnoreCase)
.map(isAlfa -> isAlfa ? ALFA_TYPE : BETA_TYPE)
.map(type -> ispropertyExists(type, apiKey))
.orElse(false);





share|improve this answer





















  • Thank you very much for your opinion, how long have you been writing in functional style? Do you use other languages besides java8?(may be haskell)
    – Pavel
    Nov 12 '18 at 1:43





















3














IMHO you’re overdoing and overcomplicating it. I agree that in general we should not pass an Optional as a parameter to a method. If you cannot require the passed apiKey to be non-null, my suggestion would be:



public boolean isTokenValid(String userAgent, String apiKey) {
LOGGER.info(String.format("userAgent : %s, Key : %s", userAgent, apiKey));
if (apiKey == null || apiKey.isEmpty()) {
return false;
}
return ispropertyExists(
userAgent.equalsIgnoreCase("ALFA") ? ALFA_TYPE : BETA_TYPE, apiKey);
}


I would find this distinctively simpler. There is no need to use an Optional for your case.






share|improve this answer





















  • I am completely agree it is simpler for those ones who get used to imperative style. :) And I agree I am overcomplicating it for people who get used to write in imperative style. I like your example too. :) Thanks for opinion! And still how would you rewrite using monads? :)
    – Pavel
    Nov 11 '18 at 12:27





















2














If you love functional style, first try to not use null, or at least don’t pass null around.



But if you must use null, here is my code for you:



public boolean isTokenValid(String userAgent, String apiKey) {
final Enum type = "ALFA".equalsIgnoreCase(userAgent) ? ALFA_TYPE : BETA_TYPE;
return
Optional.ofNullable(apiKey)
.filter(ak -> ispropertyExists(type, ak))
.isPresent();
}


PS: functional style doesnt mean trying to put everything chained and avoid temporary values. Rather, it is about the use of pure functions and immutable data. Regardless of style, our goal is to write readable and reasonable code. Pure functions and immutable data are very suitable for that goal.






share|improve this answer























  • Thanks for your opinion, I agree that it is a good Idea to get rid of optional parameter passed into method, and I did it in my example. And I agree we should not pass nulls into methods, but with current offshore team in sunny India it is impossible, unless we rewrite whole codebase and rehire offshore team, so I am curious about your opinion in such conditions. Have you considered second example I've provided?
    – Pavel
    Nov 11 '18 at 11:58












  • Yes, I edited my answer.
    – Nghia Bui
    Nov 11 '18 at 12:07










  • Thanks for your opinion. So in your example you have changed the type parameters of "ispropertyExists" function, now in your example it takes "boolean" instead of "ENUM". How would you rewrite it without changint "ispropertyExists" signature?
    – Pavel
    Nov 11 '18 at 12:11








  • 2




    No, I didnt change. The “type “variable is still an enum. Could you check it again.
    – Nghia Bui
    Nov 11 '18 at 12:13










  • Yes, you are right, I am sorry. Thanks for your opinion.
    – Pavel
    Nov 11 '18 at 12:18











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53248205%2fis-this-example-of-use-optionals-in-java-8-correct-how-would-you-rewrite-it%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














I would combine all the operations in one chained statement and return the result avoiding unnecessary Optional variables.



 return Optional.ofNullable(apiKey)
.filter(StringUtils::isNotBlank)
.map(ak -> userAgent)
.map("ALFA"::equalsIgnoreCase)
.map(isAlfa -> isAlfa ? ALFA_TYPE : BETA_TYPE)
.map(type -> ispropertyExists(type, apiKey))
.orElse(false);





share|improve this answer





















  • Thank you very much for your opinion, how long have you been writing in functional style? Do you use other languages besides java8?(may be haskell)
    – Pavel
    Nov 12 '18 at 1:43


















3














I would combine all the operations in one chained statement and return the result avoiding unnecessary Optional variables.



 return Optional.ofNullable(apiKey)
.filter(StringUtils::isNotBlank)
.map(ak -> userAgent)
.map("ALFA"::equalsIgnoreCase)
.map(isAlfa -> isAlfa ? ALFA_TYPE : BETA_TYPE)
.map(type -> ispropertyExists(type, apiKey))
.orElse(false);





share|improve this answer





















  • Thank you very much for your opinion, how long have you been writing in functional style? Do you use other languages besides java8?(may be haskell)
    – Pavel
    Nov 12 '18 at 1:43
















3












3








3






I would combine all the operations in one chained statement and return the result avoiding unnecessary Optional variables.



 return Optional.ofNullable(apiKey)
.filter(StringUtils::isNotBlank)
.map(ak -> userAgent)
.map("ALFA"::equalsIgnoreCase)
.map(isAlfa -> isAlfa ? ALFA_TYPE : BETA_TYPE)
.map(type -> ispropertyExists(type, apiKey))
.orElse(false);





share|improve this answer












I would combine all the operations in one chained statement and return the result avoiding unnecessary Optional variables.



 return Optional.ofNullable(apiKey)
.filter(StringUtils::isNotBlank)
.map(ak -> userAgent)
.map("ALFA"::equalsIgnoreCase)
.map(isAlfa -> isAlfa ? ALFA_TYPE : BETA_TYPE)
.map(type -> ispropertyExists(type, apiKey))
.orElse(false);






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 12 '18 at 1:41









ETO

1,722321




1,722321












  • Thank you very much for your opinion, how long have you been writing in functional style? Do you use other languages besides java8?(may be haskell)
    – Pavel
    Nov 12 '18 at 1:43




















  • Thank you very much for your opinion, how long have you been writing in functional style? Do you use other languages besides java8?(may be haskell)
    – Pavel
    Nov 12 '18 at 1:43


















Thank you very much for your opinion, how long have you been writing in functional style? Do you use other languages besides java8?(may be haskell)
– Pavel
Nov 12 '18 at 1:43






Thank you very much for your opinion, how long have you been writing in functional style? Do you use other languages besides java8?(may be haskell)
– Pavel
Nov 12 '18 at 1:43















3














IMHO you’re overdoing and overcomplicating it. I agree that in general we should not pass an Optional as a parameter to a method. If you cannot require the passed apiKey to be non-null, my suggestion would be:



public boolean isTokenValid(String userAgent, String apiKey) {
LOGGER.info(String.format("userAgent : %s, Key : %s", userAgent, apiKey));
if (apiKey == null || apiKey.isEmpty()) {
return false;
}
return ispropertyExists(
userAgent.equalsIgnoreCase("ALFA") ? ALFA_TYPE : BETA_TYPE, apiKey);
}


I would find this distinctively simpler. There is no need to use an Optional for your case.






share|improve this answer





















  • I am completely agree it is simpler for those ones who get used to imperative style. :) And I agree I am overcomplicating it for people who get used to write in imperative style. I like your example too. :) Thanks for opinion! And still how would you rewrite using monads? :)
    – Pavel
    Nov 11 '18 at 12:27


















3














IMHO you’re overdoing and overcomplicating it. I agree that in general we should not pass an Optional as a parameter to a method. If you cannot require the passed apiKey to be non-null, my suggestion would be:



public boolean isTokenValid(String userAgent, String apiKey) {
LOGGER.info(String.format("userAgent : %s, Key : %s", userAgent, apiKey));
if (apiKey == null || apiKey.isEmpty()) {
return false;
}
return ispropertyExists(
userAgent.equalsIgnoreCase("ALFA") ? ALFA_TYPE : BETA_TYPE, apiKey);
}


I would find this distinctively simpler. There is no need to use an Optional for your case.






share|improve this answer





















  • I am completely agree it is simpler for those ones who get used to imperative style. :) And I agree I am overcomplicating it for people who get used to write in imperative style. I like your example too. :) Thanks for opinion! And still how would you rewrite using monads? :)
    – Pavel
    Nov 11 '18 at 12:27
















3












3








3






IMHO you’re overdoing and overcomplicating it. I agree that in general we should not pass an Optional as a parameter to a method. If you cannot require the passed apiKey to be non-null, my suggestion would be:



public boolean isTokenValid(String userAgent, String apiKey) {
LOGGER.info(String.format("userAgent : %s, Key : %s", userAgent, apiKey));
if (apiKey == null || apiKey.isEmpty()) {
return false;
}
return ispropertyExists(
userAgent.equalsIgnoreCase("ALFA") ? ALFA_TYPE : BETA_TYPE, apiKey);
}


I would find this distinctively simpler. There is no need to use an Optional for your case.






share|improve this answer












IMHO you’re overdoing and overcomplicating it. I agree that in general we should not pass an Optional as a parameter to a method. If you cannot require the passed apiKey to be non-null, my suggestion would be:



public boolean isTokenValid(String userAgent, String apiKey) {
LOGGER.info(String.format("userAgent : %s, Key : %s", userAgent, apiKey));
if (apiKey == null || apiKey.isEmpty()) {
return false;
}
return ispropertyExists(
userAgent.equalsIgnoreCase("ALFA") ? ALFA_TYPE : BETA_TYPE, apiKey);
}


I would find this distinctively simpler. There is no need to use an Optional for your case.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 11 '18 at 12:21









Ole V.V.

27k62851




27k62851












  • I am completely agree it is simpler for those ones who get used to imperative style. :) And I agree I am overcomplicating it for people who get used to write in imperative style. I like your example too. :) Thanks for opinion! And still how would you rewrite using monads? :)
    – Pavel
    Nov 11 '18 at 12:27




















  • I am completely agree it is simpler for those ones who get used to imperative style. :) And I agree I am overcomplicating it for people who get used to write in imperative style. I like your example too. :) Thanks for opinion! And still how would you rewrite using monads? :)
    – Pavel
    Nov 11 '18 at 12:27


















I am completely agree it is simpler for those ones who get used to imperative style. :) And I agree I am overcomplicating it for people who get used to write in imperative style. I like your example too. :) Thanks for opinion! And still how would you rewrite using monads? :)
– Pavel
Nov 11 '18 at 12:27






I am completely agree it is simpler for those ones who get used to imperative style. :) And I agree I am overcomplicating it for people who get used to write in imperative style. I like your example too. :) Thanks for opinion! And still how would you rewrite using monads? :)
– Pavel
Nov 11 '18 at 12:27













2














If you love functional style, first try to not use null, or at least don’t pass null around.



But if you must use null, here is my code for you:



public boolean isTokenValid(String userAgent, String apiKey) {
final Enum type = "ALFA".equalsIgnoreCase(userAgent) ? ALFA_TYPE : BETA_TYPE;
return
Optional.ofNullable(apiKey)
.filter(ak -> ispropertyExists(type, ak))
.isPresent();
}


PS: functional style doesnt mean trying to put everything chained and avoid temporary values. Rather, it is about the use of pure functions and immutable data. Regardless of style, our goal is to write readable and reasonable code. Pure functions and immutable data are very suitable for that goal.






share|improve this answer























  • Thanks for your opinion, I agree that it is a good Idea to get rid of optional parameter passed into method, and I did it in my example. And I agree we should not pass nulls into methods, but with current offshore team in sunny India it is impossible, unless we rewrite whole codebase and rehire offshore team, so I am curious about your opinion in such conditions. Have you considered second example I've provided?
    – Pavel
    Nov 11 '18 at 11:58












  • Yes, I edited my answer.
    – Nghia Bui
    Nov 11 '18 at 12:07










  • Thanks for your opinion. So in your example you have changed the type parameters of "ispropertyExists" function, now in your example it takes "boolean" instead of "ENUM". How would you rewrite it without changint "ispropertyExists" signature?
    – Pavel
    Nov 11 '18 at 12:11








  • 2




    No, I didnt change. The “type “variable is still an enum. Could you check it again.
    – Nghia Bui
    Nov 11 '18 at 12:13










  • Yes, you are right, I am sorry. Thanks for your opinion.
    – Pavel
    Nov 11 '18 at 12:18
















2














If you love functional style, first try to not use null, or at least don’t pass null around.



But if you must use null, here is my code for you:



public boolean isTokenValid(String userAgent, String apiKey) {
final Enum type = "ALFA".equalsIgnoreCase(userAgent) ? ALFA_TYPE : BETA_TYPE;
return
Optional.ofNullable(apiKey)
.filter(ak -> ispropertyExists(type, ak))
.isPresent();
}


PS: functional style doesnt mean trying to put everything chained and avoid temporary values. Rather, it is about the use of pure functions and immutable data. Regardless of style, our goal is to write readable and reasonable code. Pure functions and immutable data are very suitable for that goal.






share|improve this answer























  • Thanks for your opinion, I agree that it is a good Idea to get rid of optional parameter passed into method, and I did it in my example. And I agree we should not pass nulls into methods, but with current offshore team in sunny India it is impossible, unless we rewrite whole codebase and rehire offshore team, so I am curious about your opinion in such conditions. Have you considered second example I've provided?
    – Pavel
    Nov 11 '18 at 11:58












  • Yes, I edited my answer.
    – Nghia Bui
    Nov 11 '18 at 12:07










  • Thanks for your opinion. So in your example you have changed the type parameters of "ispropertyExists" function, now in your example it takes "boolean" instead of "ENUM". How would you rewrite it without changint "ispropertyExists" signature?
    – Pavel
    Nov 11 '18 at 12:11








  • 2




    No, I didnt change. The “type “variable is still an enum. Could you check it again.
    – Nghia Bui
    Nov 11 '18 at 12:13










  • Yes, you are right, I am sorry. Thanks for your opinion.
    – Pavel
    Nov 11 '18 at 12:18














2












2








2






If you love functional style, first try to not use null, or at least don’t pass null around.



But if you must use null, here is my code for you:



public boolean isTokenValid(String userAgent, String apiKey) {
final Enum type = "ALFA".equalsIgnoreCase(userAgent) ? ALFA_TYPE : BETA_TYPE;
return
Optional.ofNullable(apiKey)
.filter(ak -> ispropertyExists(type, ak))
.isPresent();
}


PS: functional style doesnt mean trying to put everything chained and avoid temporary values. Rather, it is about the use of pure functions and immutable data. Regardless of style, our goal is to write readable and reasonable code. Pure functions and immutable data are very suitable for that goal.






share|improve this answer














If you love functional style, first try to not use null, or at least don’t pass null around.



But if you must use null, here is my code for you:



public boolean isTokenValid(String userAgent, String apiKey) {
final Enum type = "ALFA".equalsIgnoreCase(userAgent) ? ALFA_TYPE : BETA_TYPE;
return
Optional.ofNullable(apiKey)
.filter(ak -> ispropertyExists(type, ak))
.isPresent();
}


PS: functional style doesnt mean trying to put everything chained and avoid temporary values. Rather, it is about the use of pure functions and immutable data. Regardless of style, our goal is to write readable and reasonable code. Pure functions and immutable data are very suitable for that goal.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 13 '18 at 1:33

























answered Nov 11 '18 at 11:51









Nghia Bui

1,453812




1,453812












  • Thanks for your opinion, I agree that it is a good Idea to get rid of optional parameter passed into method, and I did it in my example. And I agree we should not pass nulls into methods, but with current offshore team in sunny India it is impossible, unless we rewrite whole codebase and rehire offshore team, so I am curious about your opinion in such conditions. Have you considered second example I've provided?
    – Pavel
    Nov 11 '18 at 11:58












  • Yes, I edited my answer.
    – Nghia Bui
    Nov 11 '18 at 12:07










  • Thanks for your opinion. So in your example you have changed the type parameters of "ispropertyExists" function, now in your example it takes "boolean" instead of "ENUM". How would you rewrite it without changint "ispropertyExists" signature?
    – Pavel
    Nov 11 '18 at 12:11








  • 2




    No, I didnt change. The “type “variable is still an enum. Could you check it again.
    – Nghia Bui
    Nov 11 '18 at 12:13










  • Yes, you are right, I am sorry. Thanks for your opinion.
    – Pavel
    Nov 11 '18 at 12:18


















  • Thanks for your opinion, I agree that it is a good Idea to get rid of optional parameter passed into method, and I did it in my example. And I agree we should not pass nulls into methods, but with current offshore team in sunny India it is impossible, unless we rewrite whole codebase and rehire offshore team, so I am curious about your opinion in such conditions. Have you considered second example I've provided?
    – Pavel
    Nov 11 '18 at 11:58












  • Yes, I edited my answer.
    – Nghia Bui
    Nov 11 '18 at 12:07










  • Thanks for your opinion. So in your example you have changed the type parameters of "ispropertyExists" function, now in your example it takes "boolean" instead of "ENUM". How would you rewrite it without changint "ispropertyExists" signature?
    – Pavel
    Nov 11 '18 at 12:11








  • 2




    No, I didnt change. The “type “variable is still an enum. Could you check it again.
    – Nghia Bui
    Nov 11 '18 at 12:13










  • Yes, you are right, I am sorry. Thanks for your opinion.
    – Pavel
    Nov 11 '18 at 12:18
















Thanks for your opinion, I agree that it is a good Idea to get rid of optional parameter passed into method, and I did it in my example. And I agree we should not pass nulls into methods, but with current offshore team in sunny India it is impossible, unless we rewrite whole codebase and rehire offshore team, so I am curious about your opinion in such conditions. Have you considered second example I've provided?
– Pavel
Nov 11 '18 at 11:58






Thanks for your opinion, I agree that it is a good Idea to get rid of optional parameter passed into method, and I did it in my example. And I agree we should not pass nulls into methods, but with current offshore team in sunny India it is impossible, unless we rewrite whole codebase and rehire offshore team, so I am curious about your opinion in such conditions. Have you considered second example I've provided?
– Pavel
Nov 11 '18 at 11:58














Yes, I edited my answer.
– Nghia Bui
Nov 11 '18 at 12:07




Yes, I edited my answer.
– Nghia Bui
Nov 11 '18 at 12:07












Thanks for your opinion. So in your example you have changed the type parameters of "ispropertyExists" function, now in your example it takes "boolean" instead of "ENUM". How would you rewrite it without changint "ispropertyExists" signature?
– Pavel
Nov 11 '18 at 12:11






Thanks for your opinion. So in your example you have changed the type parameters of "ispropertyExists" function, now in your example it takes "boolean" instead of "ENUM". How would you rewrite it without changint "ispropertyExists" signature?
– Pavel
Nov 11 '18 at 12:11






2




2




No, I didnt change. The “type “variable is still an enum. Could you check it again.
– Nghia Bui
Nov 11 '18 at 12:13




No, I didnt change. The “type “variable is still an enum. Could you check it again.
– Nghia Bui
Nov 11 '18 at 12:13












Yes, you are right, I am sorry. Thanks for your opinion.
– Pavel
Nov 11 '18 at 12:18




Yes, you are right, I am sorry. Thanks for your opinion.
– Pavel
Nov 11 '18 at 12:18


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53248205%2fis-this-example-of-use-optionals-in-java-8-correct-how-would-you-rewrite-it%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Bressuire

Vorschmack

Quarantine