String为空(空或null)检查:if结构 vs Java 8的Optional/filter

huangapple go评论70阅读模式
英文:

String blank (empty or null) check : if structure vs java 8 optional/filter

问题

1- 使用Apache Commons 的方法如下:

if(StringUtils.isNotBlank(str)) {
     list.add(str);
}

2- 使用 Optional 和 filter 的方法如下:

Optional.ofNullable(str)
        .filter(s -> StringUtils.isNotBlank(s))
        .ifPresent(result -> list.add(result));
英文:

Question:
Which approach is better and why

1- Using Apache Commons

if(StringUtils.isNotBlank(str) {
     list.add(str)
}

2- Optional & filter

Optional.ofNullable(str)
                .filter(s -> StringUtils.isNotBlank(s))
                .ifPresent(result -> list.add(result));

答案1

得分: 7

第一个方法更好,因为在第二个方法中,你创建了一个不必要的 Optional

但我建议使用 isNotEmpty 而不是 isNotBlank

if(StringUtils.isNotEmpty(str)){
   list.add(str)
}

要了解 isNotEmptyisNotBlank 在文档中的区别:

  • 检查一个 CharSequence 是否非空(不为 "")且非 null
  • 检查一个 CharSequence 是否非空(不为 "")、非 null非仅包含空白字符

在你的情况下,你需要检查 null 或空字符串,所以 isNotEmpty 是你的正确选择。

英文:

> Question: Which approach is better and why

The first one, because in the second one you create an unnecessary Optional


But I would suggest to use isNotEmpty instead of isNotBlank:

if(StringUtils.isNotEmpty(str)){
   list.add(str)
}

To know the difference between isNotEmpty and isNotBlank in doc:

> Checks if a CharSequence is not empty ("") and not null.

> Checks if a CharSequence is not empty (""), not null and not whitespace only.

In your case you ask null or empty, where isNotEmpty is the correct one for your case.

答案2

得分: 1

更多的附言:我的投票几乎立刻就投给了你的第一个选项。

为什么呢?简单:简洁!

第二个片段只是伪装成if语句。而这个伪装带来了大量的开销。

你的读者不仅需要查看所有字符,还需要解剖复杂的语句,然后他们需要了解Optional的工作原理,以及给定的代码实际上做了什么。

所以,除了在其他答案中概述的微小性能差异之外,真正的答案是:你应该询问你团队中的人。

如果他们都习惯于像这样使用Optional,并且他们整天都在这样做,那么也许,更好的风格是选项2。因为这就是你们所有人每天都在做的事情。但如果不是这样,正如我所说的:我建议选择更简单的代码行,可以被任何了解基本Java的人理解。

英文:

More of an addendum: my vote went almost immediately to your first option.

Why? Simply: simplicity!

The second snippet is nothing but an if-statement in disguise. And that disguise comes with plenty of overhead.

Your human readers have to look at all the characters, then they need to dissect the complex statement, then they need to know how Optional works, and what the given code actually does.

So, besides the subtle performance differences, as outlined in the other answer: the real answer: you should ask the people in your team.

If they are all used to Optional usage like here, and they do that all day long, then, maybe, the better style is option 2. Because that is what all of you do, day in day out. But if not, as said: I recommend to go with the simpler lines of code, that can be understood by anybody who knows basic java.

huangapple
  • 本文由 发表于 2020年8月10日 15:59:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63336262.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定