cactoos: TextEnvelope equals is not symmetric

https://github.com/yegor256/cactoos/blob/100885a4638555d30fb56beefbb6691108b30d0f/src/main/java/org/cactoos/text/TextEnvelope.java#L79-L90

From Java Object docs:

The equals method implements an equivalence relation on non-null object references:

It is reflexive: for any non-null reference value x, x.equals(x) should return true. It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. For any non-null reference value x, x.equals(null) should return false.

But TextEnvelope equals() implementation is not symmetric:

class Env extends TextEnvelope {
  public Env(String str) {
    super(new TextOf(str));
  }
}

class Txt implements Text {
  private final String str;
  public Txt(final String str) {
    this.str = str;
  }
  @Override
  public String asString() {
    return this.str;
  }
}

final String str = "test";
Text env = new Env(str)
Text txt = new Txt(str)
env.equals(txt) // returns true
txt.equals(env) // returns false

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 18 (11 by maintainers)

Most upvoted comments

@g4s8

I can easily implement Text somewhere with equals method, so I may get unpredictable bug which will depend on order of method calls

Two Texts are equal solely if their string contents (defined as the output of asString()) are equal. If your custom Text does not honor this then it’s not implementing the contract and it’s violating LSP.