The worst part is that, judging by his known style of seperating the function declaration and its actual code (between name and if statement), this was written by a senior developer with 5 years experience ...
Nothing againts using new lines in between, but god dangit how can you be a programmer, going through 3 years of CS degree and then 4 years of practucal experience and then write this thing?
We do as well, but the issue is that (at least anecdotally) a lot of the people coming straight out of school vs from another company or with some experience, tend to lack knowledge of coding standards, how to apply their knowledge to real world applications (you can't just build a calculator in java for a network management application) or even just typical pipeline things like version control.
I want to make sure that it doesn't seem like I'm blaming this on the individual, though. I think the issue is that a lot of curriculum is severely outdated. Once again this is largely anecdotal, but even during my time in school a lot of what they were trying to teach me was almost a decade old. I learned this stuff when I was 13. Today it's very, very insecure.
THIS looks awful and cluttered. Like someone has an obsessive compulsion to hit the enter key every 43 characters. Y'all need psychotherapy or something.
easily extensible, what if in the future you want to update how you compare numbers? now you don't need to rewrite the whole codebase just this one function
Ugh, I had an annoying dev that would do this and come to me about the buggy code "I wrote." Nope, that's our legacy code I didn't write. I added one line and the code formatter changed the indentation on most of the document.
This can happen a lot with jsx, but in my situation it was legacy jQuery and there was no enforced style guide or formatter used across the project, so it was a giant mess. When I inherited the project I started using a code formatter, so the project now looks like I wrote at least half the code when it was just the formatter cleaning up the indentation/etc.
I don't know, that could possibly be a beginner / junior we surely don't know in this case, I remember my school teached us that style back in the days. Mimicking what other seniors do is also relevant in this case.
English is a terrible language. I always amazed/impressed with anyone who picks it up as a second language. Not saying it’s your second language, just that it’s a mess in general.
Eh no worries it's actually my second language in Europe ( English is taught everywhere anyway ) I have no excuses since that's usually something we learn at a very early stage at school, like "write wrote written" or "take took taken", but eh sometimes bad habits easily come back at a certain point ! If anything, messages like this helps me memorize a little bit more that word lol
But I’d say these, while perfectly valid criticisms, are mostly cosmetic, with the except of #3 which could result in “unintended behaviour”.
I mean the function name …. Yeah should be “are”, but the function name is irrelevant from a functional point of view. And #2, I mean, it’s an extra line of source code, which will likely be optimized out in the actual instructions generated. And the same is true for #4, the function will get inlined.
Just because two versions of the code are functionally equivalent doesn't mean that the differences are merely "cosmetic" and don't matter. Clarity is important for keeping code maintainable. Every programmer who comes across a call to if (isNumbersEqual(x, y)) ... in the future is going to have to stop to dig around in the code to figure out what this function is doing and why. They wouldn't have to look twice at if (x === y) ....
the first one is petty to me, but it's understandable.
The fourth reason might be for re usability, although that's a debate whether it's better to delete it and write it in-line where it was needed or leave it refactored out, but that depends on how many times it's called and where though. There's another possibility that it was previously different and has been just left there by accident. While I think that second possibility is a stretch, I doubt that nobody on this sub hasn't done that before.
Could someone explain to me why #2 is bad? What's wrong with pure bool values? I don't understand the difference aside from "it's less total code." Plus, imo, the bool values are much easier to read, esp. at a glance...
It’s an unnecessary operation which needs (not much but still) resources. When calling the function a lot it might slow your program down. It also makes the code longer than it needs to be. The names of the variables should speak for themselves so readability should not be a problem.
Welllll not exactly, what if you put in a string '1' and an integer 1? They are both numbers. This code will say they're equal, but yours won't. To be fair it still doesn't justify this function, at all
I mean, is one of the numbers explicitly an integer? It could also be a string representation of a number. So yeah, it should be x==y if any of the input numbers could be string i suppose
I'd disagree with that: in terms of programming, the former is a string. It should be explicitly casted to avoid confusion.
'1' being equal to 1 is actually confusing: if '1' would be equal to 1, then 'one' should be equal to '1' and 1 too, since they all convey the same meaning in natural language.
A number isn't really a primary datatype though, just like a number in written language can be 3 or three, they're the same but just defined different, used in different context, and it would make sense to say that "3" is pretty much the same as "Three".
If you parse that string it will produce an integer, it contains the correct data for instantiating an integer, hexadecimal is also defined using a string in javascript, same as scientific notation, and you don't know in which context this function is actually used, which is the most important part of it all.
I totally agree with never needing to use the terrible == operator though, it will match with too much stuff which people surely don't intend for. For example, this function isNumberEqual will also return true if 2 strings of text are given.
All the context we know in this case is the function name and the implementation, while completely overengineered this is probably going to achieve what the function actually says:
function isNumberEqual(first, second) {
const firstInteger = Number(first);
const secondInteger = Number(second);
if (isNaN(firstInteger) || isNaN(secondInteger)) {
throw new Error('Not comparing numbers');
}
return firstInteger === secondInteger;
}
Establishing your correct primary type for a variable, straight out of the gate is ofcourse a good practice, but not always feasible.
You're right, I should have been more explicit about the fact that I was mostly saying that using == should not perform implicit conversions between two different datatypes, since it's not the default behaviour in other programming languages. === would have been the perfect candidate actually.
But as you said, establishing the correct primary type for any variable in a dynamically typed language is not always possible, especially when working with huge code base or when developing libraries.
As others pointed out, this could be intended design right ? Checking a string over an integer doesn't seem that gross if you think about it. I won't recommend it, but it could have some uses cases.
Pretty sure they were talking about Find/Replace == across the codebase in the absence of this function. The alternative to having this “abstraction”.
Even if so, it is more than a find and replace as it is context sensitive and not regular. Consider if (isEqual(score, getScore(thing))) how do you know which parentheses matches? You need state.
function isNumbersEqual(oldNum, newNum){
if (oldNum === newNum){
return true;
String text = "Lorem ipsum dolor sit amet, mollis aliquip oporteat ut pro, usu diceret nusquam in. Primis sensibus usu cu, pro audiam consulatu sadipscing et. Vis democritum reformidans te, ex mel ipsum disputando. No noster placerat percipitur sit, nulla omittam platonem mea at. Te erant ignota commune vis, tantas scripta inciderint nam ei.Mea ei illud viris instructior, ut detracto eloquentiam vim. Ad mea elit mollis definiebas, cu odio nonumy epicuri sed, blandit deleniti dissentias eu eos. Mea ad stet minim putant, ut minim nonumes voluptatum quo, usu ea discere invenire. Et ocurreret cotidieque pro, in quo justo congue repudiandae. Sit hinc dolorum no, an magna salutandi dissentias sea.Est dicant altera ex, admodum vituperata sed ex. Ut vero efficiendi duo, ius ea iusto ceteros, duo ad tale error. Est porro ceteros in, no ferri periculis adipiscing has. Veri apeirian sit eu. Ei per mentitum molestiae, eu vis sonet eirmod quaestio.Has alii animal legendos ut, in lucilius interesset sed, nihil persecuti vel at. Est offendit voluptua invenire in. Ne vim novum delectus menandri, et sit agam docendi minimum. Eu elit torquatos eum, ut meis essent nostro pri, at usu unum interesset reformidans.Ut mel reque civibus, te per novum suavitate voluptatibus, ut has paulo numquam. Amet verear petentium ex sed, purto liber euismod ad mea. Quod mentitum vulputate an sea, hinc aliquid abhorreant nam in. Nec at aliquam honestatis, duo ut sint vocent assueverit. Pri ferri porro tempor ne, habeo timeam praesent qui ea, in vel eruditi imperdiet. Ex mentitum senserit ius, duo mazim docendi ne.";
else {
return false;
String text = "Lorem ipsum dolor sit amet, mollis aliquip oporteat ut pro, usu diceret nusquam in. Primis sensibus usu cu, pro audiam consulatu sadipscing et. Vis democritum reformidans te, ex mel ipsum disputando. No noster placerat percipitur sit, nulla omittam platonem mea at. Te erant ignota commune vis, tantas scripta inciderint nam ei.Mea ei illud viris instructior, ut detracto eloquentiam vim. Ad mea elit mollis definiebas, cu odio nonumy epicuri sed, blandit deleniti dissentias eu eos. Mea ad stet minim putant, ut minim nonumes voluptatum quo, usu ea discere invenire. Et ocurreret cotidieque pro, in quo justo congue repudiandae. Sit hinc dolorum no, an magna salutandi dissentias sea.Est dicant altera ex, admodum vituperata sed ex. Ut vero efficiendi duo, ius ea iusto ceteros, duo ad tale error. Est porro ceteros in, no ferri periculis adipiscing has. Veri apeirian sit eu. Ei per mentitum molestiae, eu vis sonet eirmod quaestio.Has alii animal legendos ut, in lucilius interesset sed, nihil persecuti vel at. Est offendit voluptua invenire in. Ne vim novum delectus menandri, et sit agam docendi minimum. Eu elit torquatos eum, ut meis essent nostro pri, at usu unum interesset reformidans.Ut mel reque civibus, te per novum suavitate voluptatibus, ut has paulo numquam. Amet verear petentium ex sed, purto liber euismod ad mea. Quod mentitum vulputate an sea, hinc aliquid abhorreant nam in. Nec at aliquam honestatis, duo ut sint vocent assueverit. Pri ferri porro tempor ne, habeo timeam praesent qui ea, in vel eruditi imperdiet. Ex mentitum senserit ius, duo mazim docendi ne.";
}
}
(break the string in multiple lines if you are paid by the line)
Yeah, warnings most likely, like "ureachable code" or "unused variable".
If someone works at a company that pays by the length of code I suggest they find creative ways to increase their code that won't slow the product down and wont cause chaos in the important code parts.
You want a real Pro Gamer move? In the 60s and 70s IBM added tons of nops to the operating system for their 360 mainframe. Every time they released a new model they removed some nops to make the new hardware look faster.
There's an old story from a dude who worked on an early competitor for Windows in the 80s, and the moment he got into the office his new co-workers let him in on a little secret:
Basically, they were ahead of schedule, and the company allotted them a lot of time for dealing with bugs and stability issues as it was such important software. They had a few features to add here and there but ultimately, progress was progress.
They wanted to slack off some days and play some vidya in the office, watch movies, have some beers, you name it - they were pretty much unsupervised all day. So, they had put in a for loop that counts down 1,000,000 times or something like that, and reported it as a major bug based on a technical limitation they were working around the clock on.
Every time management wanted to see progress, they would take a 0 off of the iteration count, and showed the software working 10x faster (or whatever multiplier they came up with that build), or they would comment out one of the ones they laid out to stutter it on certain actions.
They made it slow in easily adjustable ways and then slowly removed the slowness to report their great work to management.
If someone works for a company that pays for length of code it probably makes sense to start looking for another company. It was a bad idea when people started doing it and it's a bad idea now...
I wrote this really early and missed the return right before that someone pointed out to me, so I guess it probably wouldn’t compile in several languages. But otherwise yeah that might work lol
Thank you. My very limited understanding of JS indicated that this works identically to a single line comparison for any combination of nums and strings.
It bothers me that he/she used old and new. That implies that the numbers will be supplied in the order they were created. "First" and "Second" would have been better names.
Hasn't been proper English for a long long time to use they as a singular. Recent invention....useful, but it still sounds like nails on a chalkboard to me.
There's an obvious problem with the use of they as singular. Yeah, according to the current APA and MLA it is fine, but it has not been so for a long time.
So, what do you say when referring to a person whose gender you don't know? "He-slash-she"? "The person"? Or do you just pick a random pronoun and hope for the best? There are languages where you have to pick from one of these options, and it's always a bit awkward (coming from a bilingual English/German speaker) - having a gender-neutral pronoun is a really nice feature of English which we absolutely should make the most of.
You must be younger than 30 because you clearly have no memory or awareness of English teachers drill APA and MLA into us saying, "USE HE OR SHE, NEVER USE THEY BECAUSE ITS SINGULAR."
The rules of the game changed very recently considering the history of the English language.
I didn't say they was useless. It is useful to use it as a single pronoun because English does not have a singular genderless pronoun except "it."
It's useful but it's academic official use is a recent invention in response to the de-gendering cultural movement.
Actually, no, I'm not under 30. Maybe there are regional differences, but I was never taught that. However, the fact that you were at the very least proves that people were using it when you were in school - why else would they bother teaching it as a rule? This seems to me like one of these pseudo-linguistic rules that arose in the 19th century for no reason other than that teachers of the time had ridiculous prescriptivist notions about language - like the "no split infinitives" rule, which was just blatantly made up by pedants.
It's useful but it's academic official use is a recent invention in response to the de-gendering cultural movement.
This is a convenient right-wing narrative, but it overlooks the fact that there have always been situations where you're talking about someone without knowing their gender, as well as the fact that this use of "they" goes back centuries. What is relatively recent is the use of "they" by people who prefer not to be gendered, but the use to refer to unknown people goes back way further than that (e.g. in sentences such as "someone's left their glasses behind" - are you seriously telling me you would say "someone's left his or her glasses behind"?)
Why downvoted? You may not like it, but every word if this is true. It's a recent invention in the scholarly world. I know there are some oddball linguistic cases, but "ain't" has similar usage without being proper.
Just to play bad coder's advocate, there is one somewhat legit use case - when you need to abstract over several binary functions, e.g. in a visitor, like so:
function visit(other, withFunc) {
return withFunc(this, other);
}
function add(a, b) {
return a + b;
}
node.visit(otherNode, add);
node.visit(otherNode, isNumbersEqual);
Again, the original coder, being way more experienced in the ways of zen and computing, cleverly kept backwards compatibility on the top of their mind.
Well, obviously there is at least one return statement missing (outside the if/else statement, just in case). And the whole thing needs to be wrapped in a try catch. And why isn't the function declared with async?
As always, it depends on the context. What's going wrong in this function (among other things) is that it's not specifically comparing numbers because putting in 2 identical strings of text will also return true.
An edge this function has is that you can compare a string number to an integer number isNumberEqual('1', 1) will return true, and I think this is correct, there are use cases for it. Else it would've been isIntegerEqual.
So, you at least need to make sure you can't put strings of text into here.
This is awfully overengineered though. Usually you know if one of your sources is a string and you would parse those to an integer before doing a regular old ===.
EDIT: had to change up falsey checks to isNaN checks, else it wouldn't match a value of integer 0
Usually there's a backstory behind weird code like this when I run into it. Like a function that used to do something more complex before a feature was removed and how the function is just an empty shell. And rather than update every reference to the old function you just delete the old functionality out of the function body.
This seems to be a non-compiled language like JavaScript, though these kind of optimizations are certainly possibly (idk if JS does them though). C with gcc and -O3 optimzations would probably inline this code which results in oldNum == newNum.
I know people are being silly about ===, but there are legitimate use cases for that. But oldNum == newNum is already a boolean; just return that already.
152
u/froggy_Pepe Jun 07 '21
There is so much wrong with this.
53
u/sixtyfifth_snow Jun 07 '21
At first sight I thought it's not that bad but soon I realized it's a javascript code and sooooo gross!
516
u/DirectControlAssumed Jun 07 '21
"Yes, just in case EcmaScript 2050 will change the behavior of ==, we should avoid copying it over the whole code base."
337
u/toi80QC Jun 07 '21
Useful if you ever get paid per character, I guess..
53
u/xiipaoc Jun 07 '21
Well... is they?
24
u/literallyfabian Jun 07 '21
there's most likely a npm package for this
31
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jun 07 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
45
u/FlashyBumblebee Jun 07 '21
To be honest this would also work for 5 and "5"
11
u/oM4TY Jun 07 '21
this function is just as useful as pouring water on your head from a bottle when you are in a swimming pool
5
u/adzy2k6 Jun 07 '21
It bothers me that he/she used old and new. That implies that the numbers will be supplied in the order they were created. "First" and "Second" would have been better names.
1
u/Death_Strider16 Jun 08 '21
I've been drinking and am a little dumb. Explain to me the horror that is this code
3
u/[deleted] Jun 07 '21
Just to play bad coder's advocate, there is one somewhat legit use case - when you need to abstract over several binary functions, e.g. in a visitor, like so:
Totally made up nonsense example of course.
3
u/snafu918 Jun 07 '21
Lol I’ve seen so much worse
5
u/YllMatina Jun 07 '21
So whats the best course here? Using comparable?
2
u/jeff_coleman Jun 07 '21
Not great, but at least it's readable.
2
u/amroman42 Jun 07 '21
Well it works…
2
u/[deleted] Jun 07 '21
Usually there's a backstory behind weird code like this when I run into it. Like a function that used to do something more complex before a feature was removed and how the function is just an empty shell. And rather than update every reference to the old function you just delete the old functionality out of the function body.
2
u/fractalimaging Jun 07 '21
Wait, I don't get it. This looks like it makes sense...
2
u/QuantumEternity99 Jun 08 '21
I think I had more of a stroke reading “abodmination” than the code.
2
u/veedant Jun 08 '21
I've lost my will to live
2
u/_deton8 Jun 09 '21
When the == operator stops working
2
u/mattamatrow Jun 07 '21
Not even the extra = to get ===
:(
1
u/jack_skellington Jun 07 '21
Forgetting the programming angle, the grammar of "is numbers equal" is making my eye twitch.
1
u/[deleted] Jun 07 '21
Grammatical error in line #1!
1
u/Nick433333 Jun 07 '21
Wouldn’t this get optimized by the compiler to
return oldNum == newNum? Or is it so bad that the user has fooled the compiler into worse code1
u/[deleted] Jun 07 '21
Just need to put this code in FunctionServiceAdapter class. So everyone knows you are software architect
1
u/PsCustomObject Jun 07 '21
For some weird reason I love this! 😳
1
u/cprgrmr Jun 07 '21
Some people are paid by the line.
1
u/HasanTheSyrian_ Jun 07 '21
I assume this bad because you do that logic inside the function itself instead of making a function for it?
1
u/crazyjoker96 Jun 07 '21
The more dangerous things are the else in the new line
1
u/Not_Sugden Jun 07 '21
i wonder of they copied the function body for strings, objects, and whatever tf else too
1
u/AsleepPersimmon1365 Jun 07 '21
The facts that there is a full function for this makes this bad, but the name of the function makes it even worse.
1
u/gent861 Jun 07 '21
Im humbly wannabedeveloper asking why they even put this as a function?
1
u/KyleDrogo Jun 07 '21
> is numbers
1
u/ThatCrankyGuy Jun 07 '21
That's just future proofing the possibility of overloaded type conversion.
Proper engineering, this stuff /s
1
u/Alvatrox4 Jun 07 '21
Just to be sure, everything is posible in JS
1
u/shut_up_if_your_dumb Oct 12 '21
Let's be honest, everyone did this at the beginning.
1
u/serieousbanana Jun 14 '22
It is obviously fake
1
u/SaltyMini Jun 07 '21
What would be the optimal way of doing this?
-3
u/RyanNerd shameless Jun 07 '21
The real abomination is that even after more than 20 years we're stuck with the idiotic language of Javascript exclusive to the web browser.
0
u/[deleted] Jun 07 '21
[deleted] — view deleted comment