Create a compiler warning for enum.ordinal

Working Java 7 + .... Suppose we created an enumeration:

enum Foo{ FOO, BAR }

then Foo.FOO.ordinal() == 0. However, if I reorder the listing, say:

enum Foo{ BAR, FOO }

then Foo.FOO.ordinal() == 1. This is surprising for most people because they find reordering fields to be a “safe” operation. Not surprisingly, Java recommends using in most cases enum.ordinal(). There are many alternatives, most obviously (and self-documenting), linking each enum value with an int.

Unfortunately, some people in my company did not receive the note, and our old code uses the method .ordinal()everywhere, depending on the fundamental way of communicating between the int value and the enum value. When I have time, I look through refactoring as well, but that doesn't stop me from using new code .ordinal()that introduces potentially untraceable errors.

So! Suppose I have an enumeration with a lot of structure associated with it. Is there any way to mark it .ordinal()as unsafe so that if someone uses (say) a Foo.FOO.ordinal()compiler warning will be generated?

I agree to use external packages for this purpose, but would prefer that they not be too obscure.

+4
2

enum , , ordinal() .

, , Java , ordinal() "" , .

, . @Henry, , , ordinal() :

  • , ordinal(), .
  • int toInteger(), .
  • static EnumClassName fromInteger(int v) ""
  • ordinal() toInteger() fromInteger().
+1

XPD PMD?

//PrimaryPrefix/Name [end-with (@Image, '.ordinal')]

XML :

<rule name="DontUseEnumOrdinal" message="Please no enums ordinal"
    class="net.sourceforge.pmd.lang.rule.XPathRule" language="java">
    <description>We don't take kindly enum ordinal() round these parts</description>
    <priority>3</priority>
    <properties>
        <property name="xpath">
            <value><![CDATA[//PrimaryPrefix/Name[ends-with(@Image, '.ordinal')]]]></value>
        </property>
    </properties>
    <example><![CDATA[MyEnum.MY_VALUE.ordinal(); //is bad
        MyEnum.MY_VALUE.index(); //is better]]>
    </example>
</rule>
0

Source: https://habr.com/ru/post/1662171/


All Articles