Javaの8での使用のOptionalsのこの例は正しいですか?どのようにそれを書き換えるでしょうか?

パベル:

私は、Javaの8 Optionalsを使用し始めました。そして私はそれが例の「コードの臭い」と私はそれにあなたの意見を見に興味を持っていますので、Javaの8とoptionlasと機能(宣言型)スタイルを使用して、それを書き換えるしたいです、この方法を共有したいと思います。のは、この方法を考えてみましょう:

  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()));
    }
}

「ispropertyExists」戻りboolean型、および「ALFA_TYPE」と「OMEGA_TYPEは、」列挙型の定数です。そこで、以下、私は読みやすさを改善し、機能的な思考様式を練習するつもりでこのメソッドを書き直した方法です。私はあなたがそれを改善するためにあなたができると思えば、私はあなたの意見や、あなたの方法の例を感謝し、私の考えと私はそうと、そのようにした理由を説明して、コメントを追加しました。

    /**
 * 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);
}

ありがとうございました。

ETO:

私は1つの連鎖文ですべての操作を組み合わせて、不要な回避結果返すOptional変数を。

 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);

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=199310&siteId=1
おすすめ