Better equals pattern

Many Vaadin core sources, book examples and some add-ons sources use bad equals pattern:

public mymethod (MyType value) {
if (cellStyle != null && !cellStyle.equals(“”) --verbose
or just value.equals(“sometext”) --unsafe
or just value.equals(“”) --unsafe

i.e. variable.equals(“const”)

It’s better to use good pattern:


“const”.equals(variable)

  • it handles null variable values too (of course “const” must be public static final String SOME_CONST)

Also is good to have
SomeVaadinCoreUtilClass with:

/**

  • Is CharSequence (incl String) null or empty (length == 0).
  • @see #hasLength(CharSequence)
    */
    public static boolean isEmpty (@Nullable final CharSequence str) {
    return str == null || str.length() <= 0;
    }

for source clarity

Thanks for noticing this, the reverse notation is safer.

The only thing which I’m a bit worried about is readablity of code, it always suffers a bit from unconventional notations. In a manual, you want to have code examples as easily readable as possible. Oh well, probably not a very significant issue in this case.

CONST.equals(variable) is industry accepted pattern.

IntelliJ IDEA, for example, has inspection to catch this (and automatically flip).

It’s like C/C++ pattern: if (const == variable) to prevent if (variable = const) mistakes.

Many, if not all, people I know copy-paste the examples in the book or sampler to get going. See this as an opportunity to spread good practices !

The main pain is the MIX: in same source you can find both “equals” variants.

Small note about Enums:
Enums are singletons, so you can compare them with ==.

ex:
if (var == MyEnum.MY_ENUM_ITEM1) …

(or in C/C++ style: MyEnum.MY_ENUM_ITEM1 == var :wink:

Ok, I grepped through the book and fixed the cases. There
weren’t actually very many occurrences
in the book itself. In the book examples,
there were a lot
, but most of them are not in the actual code examples. They were luckily simple to fix with just sed.

About 2/3 of equals expressions (141 vs 92 with a simple search) in the core library seem to use the unsafe notation.


ticket 6620

Ahh… “Yoda Conditions” are what you speak of, young jedi coder…


http://united-coders.com/christian-harms/what-are-yoda-conditions