How to properly return Optional<> of a method?

偶尔善良 提交于 2020-01-22 11:40:06

问题


I have read a lot of Java 8 Optional and I do understand the concept, but still get difficulties when trying to implement it myself in my code.

Although I have serached the web for good examples, I didn't found one with good explanation.

I have the next method:

public static String getFileMd5(String filePath) throws NoSuchAlgorithmException, IOException {
    AutomationLogger.getLog().info("Trying getting MD5 hash from file: " + filePath);
    MessageDigest md = MessageDigest.getInstance("MD5");
    InputStream inputStream;
    try {
        inputStream = Files.newInputStream(Paths.get(filePath));
    } catch (NoSuchFileException e) {
        AutomationLogger.getLog().error("No such file path: " + filePath, e);
        return null;
    }

    DigestInputStream dis = new DigestInputStream(inputStream, md);
    byte[] buffer = new byte[8 * 1024];

    while (dis.read(buffer) != -1);
    dis.close();
    inputStream.close();

    byte[] output = md.digest();
    BigInteger bi = new BigInteger(1, output);
    String hashText = bi.toString(16);
    return hashText;
}

This simple method returns the md5 of a file, by passing it the file path. As you can notice, if the file path doesn't exists (or wrong typed) a NoSuchFileException get thrown and the method return Null.

Instead of returning null, I want to use Optional, so my method should return Optional <String>, right?

  1. What is the proper way of doing it right?
  2. If the returned String is null - can I use here orElse(), or this kind of method should be used by the client side?

回答1:


Right.

public static Optional<String> getFileMd5(String filePath)
        throws NoSuchAlgorithmException, IOException {

        return Optional.empty(); // I.o. null

    return Optional.of(nonnullString);
}

Usage:

getFileMd5(filePath).ifPresent((s) -> { ... });

or (less nice as undoing the Optional)

String s = getFileMd5(filePath).orElse("" /* null */);


来源:https://stackoverflow.com/questions/37811794/how-to-properly-return-optional-of-a-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!