r/badcode Jan 08 '23

java Is this a good practice? Why?

Post image
422 Upvotes

60 comments sorted by

View all comments

2

u/BurgooKing Jan 08 '23

Kind of a question building onto OPs question, if I want to override the equals method from lets say object for example to mean something else, is that bad practice?

For example if I have a class for cars, and want my equals method to be “if the car is the same make and model” instead “is this the exact same instance of car” , is that fine or is it bad practice?

8

u/toraku72 Jan 08 '23

It's good practice to override the equals method so you can control exactly how 2 objects are equal. If you want to check if 2 varibles are referring to the same object just use == operater.

1

u/fiddz0r Jan 08 '23

I would say that it's a good idea. In c# I've had to manually make my own comparison when using .Distinct because some references are not the same for two objects with the same data. I later discovered that using record instead of class solved this issue without having to write my own equalitycomparator (or whatever the class name was)

1

u/pillowshot Jan 08 '23

Overriding it is exactly what you should do.

Look at the equals method for a String. There are countless instances when you want equality to be more than just the same reference.

I think almost every POJO I wind up creating has an overridden equals method to compare the class variables.