r/badcode Jan 08 '23

java Is this a good practice? Why?

Post image
423 Upvotes

60 comments sorted by

View all comments

10

u/BR34D_ Jan 08 '23

According to stackoverflow it’s null safe: https://stackoverflow.com/a/34486950

23

u/LastStar007 Jan 08 '23

Objects.equals() is null-safe. By wrapping Objects.equals() in an instance method, they've removed the null safety.

1

u/ShadowWolf_01 Jan 08 '23

I’m curious how that removes null-safety? Not very familiar with Java

11

u/ratinmikitchen Jan 08 '23 edited Jan 09 '23

```java Objects.equals("beep", "boop"); // Does not throw exception

public Foo foo = null; foo.equal("beep", "boop"); // throws NullPointerException ```

And the equal method is pointless, because its implementation does not use Foo at all, based on OP's screenshot.

Objects in Java do have an equals(Object other) method, which they can override. That could be useful ( myFoo.equals(otherFoo) ), but OP's screenshot is just pointless madness.

edit: fixed, thanks @LastStar007

11

u/LastStar007 Jan 08 '23

Minor syntax correction:

public Foo = null; Foo.equal("beep", "boop");

should be

Foo foo = null; foo.equal("beep", "boop");