Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using equals with string in enum in Java

Tags:

java

enums

equals

Assume we have the next enum and I want to add equals(String) method to it, because other people that working with the same code usually make a mistake comparing enum with string using equals method.

public enum SomeEnum {
    CONSTANT1("DATABASE_CONSTANT1"),
    CONSTANT2("DATABASE_CONSTANT2");

    private final String databaseConstant;

    SomeEnum(String databaseConstant) {

        this.databaseConstant = databaseConstant;
    }

    public String getDatabaseConstant() {
        return databaseConstant;
    }

    public boolean equals(String databaseConstant) {
        return getDatabaseConstant().equals(databaseConstant);
    }
}

Question: are there any pitfalls in using the approach like this?

like image 330
Oleksandr Tarasenko Avatar asked Apr 17 '26 05:04

Oleksandr Tarasenko


1 Answers

Some of the contracts bound to equals(..) would be violated. Especially symmetry. This can lead to all kinds of problems in the future.

https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)

I recommend not to support the miss use of equals(..) 'other people' do.

To find code early that use equals(String ) you could do this:

@Deprecated
public boolean equals(String databaseConstant) {
  throw new IllegalArgumentException("Never use equals(String) for SomeEnumtype "); 
}

The @Deprecated will most IDE mark any call as a warning.


UPDATE
As davidxxx wrote in his comment & answer if you use e.g. sonar the warning of sonar would be sufficient to cope with your problem without adding the 'dead code' I offered as a solution above.

like image 102
MrSmith42 Avatar answered Apr 21 '26 02:04

MrSmith42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!