String.equals()参数排序 [英] String.equals() argument ordering

查看:150
本文介绍了String.equals()参数排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在最近的回答

I recently received a downvote for using the following in a recent answer:

String word = ...;
if ("s".equals(word) || "y".equals(word)

由于使用了yoda条件而给出了downvote。我要求进一步解释但没有提供。我更喜欢这种风格以避免可能的 NullPointerException

The downvote was given due to using a "yoda condition". I asked for further explanation but none was provided. I prefer this style to avoid a possible NullPointerException.

这是一种糟糕的编码风格吗?如果是这样,为什么?

Is this a poor coding style? If so, why?

推荐答案

Bill Pugh在Devoxx 2011上提出了这个问题。绝大多数人选择xyz.equals(str)的形式。我和Bill在一起,现在更喜欢 str.equals(xyz)

Bill Pugh asked this question at Devoxx 2011. The vast majority of people went for the form "xyz".equals(str). I am with Bill, now preferring str.equals("xyz").

我们在合理可能的早期发现错误是Java传统的基础NPE非常常见。我们希望尽快将这些空值排除。

It's fundamental to the Java tradition that we find errors as early as reasonably possible. NPEs are exceptionally common. We want to route these nulls out as soon as possible.

如果您期望引用可能 null ,那么我并不特别反对向后的表示法。很明显,更容易理解可能有一个 null 一个单独的 null 检查,但应该很好地理解相反的顺序,并充分区分代码与 null 的正常情况禁止使用。

If you're expecting the reference to maybe null, then I don't particularly object to the backwards notation. It's nice to be explicit and easier to understand that there may be a null with a separate null check, but the reverse order should be well understood and sufficiently differentiate the code from the normal case where null is forbidden.

在安全性方面,一些容易出错的容忍漏洞就是漏洞。

Working in security, some of the bugs null-tolerance accommodates are vulnerabilities.

这篇关于String.equals()参数排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆