Looks better. I personally think the top one looks cleaner, and I'm 99% sure the compiler will optimize out any underlying differences. Its a bit rubbish that it wastes 3 lines of code to write out the function definition though.
This is certainly by far not the worse code ever seen on here.
This is my bane. I've got a coworker who renames all imports to php names of the method or wraps them to behave the same way. Which has fucked us over in the past when he's changed the behavior of parsers. Half the people in the department & everyone on my team except myself are php devs, so nobody complains, but it drives me mad.
A very long time ago, in a company far, far, away, I was asked to review a "C programming guidelines" proposal (because I was at the time one of the very few with C experience). It contained such gems as:
switch/case use is prohibited
start all you code with #define BEGIN { and #define END } and use BEGIN/END instead of curlies.
I rebuked it in a mail that made me some corporate enemies but also a lot of friends :)
In Java you can achive both with Objects.equal. If you make a static import of equals, the result will look like your first example. If not, it'll looke like the 2nd
This is one of the downsides of the implicitly passed this object, people don't realize it's there and will write methods that don't even use them when they should've made a static method instead.
Once I thought about OOP as having a pre-partially-applied this for methods, it finally made some sense, but functions were always simpler to work with. I think the patterns they teach lead folks to overcomplecting code when it comes to OOP—I know that was my experience.
It's not just thinking of methods in that way to make it click, it helps you truly understand it because that is actually what happens. When you make a method with no parameters, it actually creates a function with ONE parameter, that being an object of the class that you are writing the method for. Methods also always have an implicit null-check before they run the code you put in it. If you try calling the method from this post on a null-object, it will throw an exception even though that doesn't matter because this is never even used.
It's one of the reasons I think that to learn programming you shouldn't start with an object oriented language. A method is simply a more complex function, so when you are learning, start with the simpler variant! A static method is really just a normal function again, but adding that keyword makes it seem more complicated to beginners, because it is still connected to this "class" thing and now it suddenly can't access the member variables anymore, "that's weird". I've tutored people learning java and explaining these things is surprisingly hard when they don't have any established knowledge of what a simple function is because they worked with methods from the start.
Aside from that I also think/agree that OOP shouldn't be the industry standard that it is, for a variety of reasons including the unnecessary complexity you mentioned, but also performance loss from pointer indirection that is inherent to OOP. But I shouldn't say that too loud, people get really defensive when you criticize OOP.
I would say that creating a wrapper function that does a single function call itself is not a good practice in general. It simply obfuscates what is really happening in your code in the places where you call the wrapper function.
(Disclaimer: usages of the word "you" below are directed at the author of the code, not necessarily OP. It was easier to answer the question this way.)
Like others have said, wrapping a one-line function call in another method is generally pointless. There are times when you should/need to, but if you don't have a specific reason, then don't.
But the biggest problem here is the method signature. For illustration, let's say the code snippet you posted is from the Car class. You can call Objects.equals(a, b) anywhere. But the public boolean equal(Object a, Object b) that you wrapped around it can only be called by a Car instance. Notably, the Car that's calling the method doesn't have to be one of the Cars you want to compare:
Car a, b;
Car c = new Car();
c.equal(a, b);
This is confusing and misleading, because people reading this method signature tend to assume (based on how they've used other equals() methods) that the object doing the calling is one of the objects being compared, but this isn't necessarily the case. (The proof is that no one else in this thread seems to have noticed this possibility—every commenter's intuition is telling them something that isn't quite true.)
All together, the point is that:
a) I don't think you have a use-case for this method,
b) But if you did, the two parameters make it look like you want to write something similar to the Objects.equals() method. But that method already exists, so defining a new method that does nothing but call it is as useless as nipples on a breastplate.
c) But if you did want to define a new method, that acted like Objects.equals() but wasn't exactly the same thing, that method should be static, so that we'd use it in a similar manner as Objects.equals(): Car.equals(car1, car2), not car3.equals(car1, car2).
d) And if you did want to lay out what it means for two Cars to be equal in the eyes of your application, the better way to do it is by overriding the built-in, non-static equals() method. This is both i) more what other programmers, and eventually yourself, will be used to, which means intuition will be working for you instead of against you, and ii) more how object-oriented programming works. In general, OOP is all about objects defining their own behavior. So the more semantically correct question is "Is this other object equal to me?" (object's point of view), not "Are these two objects equal?" (omniscient third party).
e) But if you did need to define your own equals method, and you had good reasons not to override the built-in Object.equals(Object obj), and you wisely chose to make Car.equals(Object a, Object b) static instead of requiring an irrelevant Car object to call the method that may or may not be one of the Cars being compared, then you should still call it equals(), not equal(). I don't like to split hairs over names, but trust me, 2 years from now after you've become an accomplished Java programmer and you've forgotten everything about this project, when you Ctrl-F for "equals", you'll want this to come up.
I know it sounds like I'm busting your ass 5 times for three lines of code, but I promise that's not my intent. What I really want to get across is how an ounce of prevention is worth a pound of cure. You solve all 5 issues by deleting this method entirely. If you have good reasons why that's not an option, you proceed down the list, only moving to the next option when you truly understand what the best practice is and what makes you unable to apply it in this case.
That was a lot more long-winded than I thought it would be, but I hope it provides OP some clarity about where the pitfalls with this implementation are and how to avoid them going forward. Equals methods are surprisingly complex and subtle little buggers in Java, and that's why it pays to have a solid understanding of OOP principles.
If you override Object.equals(Object obj), then Objects.equals(Object a, Object b) will work out of the box--no need to write your own static method, and no irrelevant instance required. This has the added benefit that when you're writing your own instance method equals(), you know that this is not null, which mildly simplifies the logic you need to write.
Objects.equals("beep","boop");// Does not throw exception
publicFoo 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.
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?
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.
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)
Depends on the language of course, but in Java the main reason I would see is if you want to streamline handling of primitive types (int, double, etc) with objects.
The value of Objects in Java can not be compared using ==, whereas for primitive types, .equals does not work. So if you made overloads of the form
boolean equals(int a, int b) { return a == b; }
You could happily write equals(a, b) for both primitive and non-primitive types. And as mentioned, handle null-pointers in the first argument.
Though if I were to guess, it stems from someone copy-pasting a larger snippet of code from another language
One use of creating a static/third party function like this is that it can handle null objects (with some added logic, of course). foo.equals(bar) will always throw a null pointer if foo is null (probably also if bar is null), but equal(foo, bar) can have built in null value checks.
edit: though it looks like Java might do some special stuff to make foo.ewuals(bar) still work with a null foo
The only reason to have a function like this is if you believe the function might change in the future and therefore you won't have to duplicate the changed code later, so no, it is not a good practice in this case.
Why do you require an instance of the type to check two different instances of the type, and if you wanted to check this object why did you give it two parameters?
275
u/RiddSann Jan 08 '23
I think using Objects.equals is good practice, but I don't see the point of creating a method for that ? I mean, it is a method, no need to wrap it.
161
u/EvaristeGalois11 Jan 08 '23
Using Objects#equals? Yes, very good to use.
Writing a useless instance method to wrap a static ones? Nope, very stupid.
81
u/[deleted] Jan 08 '23
It's anti-OOP. A public method on a concrete instance of a class, to check if two unrelated objects are equal?
Why would an object need to check if two other objects are equal?
13
u/[deleted] Jan 08 '23
Using most methods from the Objects utility class is good practice, wrapping them like that is not...
24
u/[deleted] Jan 08 '23
I would say that creating a wrapper function that does a single function call itself is not a good practice in general. It simply obfuscates what is really happening in your code in the places where you call the wrapper function.
6
u/LastStar007 Jan 08 '23
(Disclaimer: usages of the word "you" below are directed at the author of the code, not necessarily OP. It was easier to answer the question this way.)
Like others have said, wrapping a one-line function call in another method is generally pointless. There are times when you should/need to, but if you don't have a specific reason, then don't.
But the biggest problem here is the method signature. For illustration, let's say the code snippet you posted is from the Car class. You can call Objects.equals(a, b) anywhere. But the public boolean equal(Object a, Object b) that you wrapped around it can only be called by a Car instance. Notably, the Car that's calling the method doesn't have to be one of the Cars you want to compare:
This is confusing and misleading, because people reading this method signature tend to assume (based on how they've used other equals() methods) that the object doing the calling is one of the objects being compared, but this isn't necessarily the case. (The proof is that no one else in this thread seems to have noticed this possibility—every commenter's intuition is telling them something that isn't quite true.)
All together, the point is that:
a) I don't think you have a use-case for this method,
b) But if you did, the two parameters make it look like you want to write something similar to the Objects.equals() method. But that method already exists, so defining a new method that does nothing but call it is as useless as nipples on a breastplate.
c) But if you did want to define a new method, that acted like Objects.equals() but wasn't exactly the same thing, that method should be static, so that we'd use it in a similar manner as Objects.equals(): Car.equals(car1, car2), not car3.equals(car1, car2).
d) And if you did want to lay out what it means for two Cars to be equal in the eyes of your application, the better way to do it is by overriding the built-in, non-static equals() method. This is both i) more what other programmers, and eventually yourself, will be used to, which means intuition will be working for you instead of against you, and ii) more how object-oriented programming works. In general, OOP is all about objects defining their own behavior. So the more semantically correct question is "Is this other object equal to me?" (object's point of view), not "Are these two objects equal?" (omniscient third party).
e) But if you did need to define your own equals method, and you had good reasons not to override the built-in Object.equals(Object obj), and you wisely chose to make Car.equals(Object a, Object b) static instead of requiring an irrelevant Car object to call the method that may or may not be one of the Cars being compared, then you should still call it equals(), not equal(). I don't like to split hairs over names, but trust me, 2 years from now after you've become an accomplished Java programmer and you've forgotten everything about this project, when you Ctrl-F for "equals", you'll want this to come up.
I know it sounds like I'm busting your ass 5 times for three lines of code, but I promise that's not my intent. What I really want to get across is how an ounce of prevention is worth a pound of cure. You solve all 5 issues by deleting this method entirely. If you have good reasons why that's not an option, you proceed down the list, only moving to the next option when you truly understand what the best practice is and what makes you unable to apply it in this case.
That was a lot more long-winded than I thought it would be, but I hope it provides OP some clarity about where the pitfalls with this implementation are and how to avoid them going forward. Equals methods are surprisingly complex and subtle little buggers in Java, and that's why it pays to have a solid understanding of OOP principles.
9
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 08 '23
Image Transcription: Code
I'm a human volunteer content transcriber and you could be too! If you'd like more information on what we do and why we do it, click here!
3
u/StrikingChallenge389 Jan 08 '23
Someone read something about overriding the equals method being a good idea in certain cases, but really missed the point
10
u/BR34D_ Jan 08 '23
According to stackoverflow it’s null safe: https://stackoverflow.com/a/34486950
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?
2
u/GodlessAristocrat Jan 08 '23
No. Because it's useless code that does nothing but obfuscate class/type/object methods.
2
u/AlarmingBarrier Jan 08 '23 edited Jan 08 '23
Depends on the language of course, but in Java the main reason I would see is if you want to streamline handling of primitive types (
int,double, etc) with objects.The value of Objects in Java can not be compared using
==, whereas for primitive types,.equalsdoes not work. So if you made overloads of the formYou could happily write
equals(a, b)for both primitive and non-primitive types. And as mentioned, handle null-pointers in the first argument.Though if I were to guess, it stems from someone copy-pasting a larger snippet of code from another language
2
u/Verdiss Jan 08 '23
One use of creating a static/third party function like this is that it can handle null objects (with some added logic, of course). foo.equals(bar) will always throw a null pointer if foo is null (probably also if bar is null), but equal(foo, bar) can have built in null value checks.
edit: though it looks like Java might do some special stuff to make foo.ewuals(bar) still work with a null foo
2
u/chaiwala07 Jan 08 '23
Whats the point, just use the return directly without wrapping it in a function
2
u/valzargaming Jan 08 '23
The only reason to have a function like this is if you believe the function might change in the future and therefore you won't have to duplicate the changed code later, so no, it is not a good practice in this case.
1
u/Quentinooouuuuuu Jan 08 '23
You should override Object#equals but method content is correct
1
u/[deleted] Jan 08 '23
Beauty😍
1
u/Sindarin27 Jan 08 '23
I can think of just about one case where this is useful, and it's if you plan to have a subclass that overrides the equal method.
1
u/elderly_millenial Jan 08 '23
This is a bad idea. Putting it into a method leaves you open to NPEs. Moreover, the arguments have nothing to do with object that you’d be calling.
1
u/[deleted] Jan 08 '23
Java is pain someone can give me a book for been good ?
1
u/8BitFlatus Jan 08 '23
That extra function/method does not add anything to the code.
1
u/[deleted] Jan 08 '23
Why do you require an instance of the type to check two different instances of the type, and if you wanted to check this object why did you give it two parameters?
1
u/cofffffeeeeeeee Jan 08 '23
Horrible practice:
1
u/Round_Log_2319 Jan 09 '23
Someone’s skimmed through uncle bobs classes…
1
u/CastleNugget Jan 09 '23
No, it’s unneeded abstraction.
1
u/olafurp Jan 09 '23
This is to encapsulate the behavior so it can be changed later.
1
u/[deleted] Jan 15 '23
My man just import static java.util.Objects.equals will give you your short method call.
-2
u/david_daley Jan 08 '23
Probably the result of a pedantic senior dev that said the you must always override
equal