r/badcode • • Mar 01 '21

js Defensive programming or something idk

Post image
907 Upvotes

55 comments sorted by

215

u/bnz_ Mar 01 '21

Fun fact: this code is somehow legacy and no one can remove all those useless &&

19

u/SnooMarzipans436 Mar 01 '21

If your boss won't let you change this because it's "legacy and no one knows if it will break", you need to find a better company to work for lol

14

u/bnz_ Mar 01 '21

Totally agree with you

0

u/[deleted] Mar 01 '21

[deleted]

78

u/JuhaJGam3R Mar 01 '21 edited Mar 01 '21

Nah. Any compiler will turn x == c1 && x != c2 into x == c1, same with x == c1 && x == c2 turning into false turning into removal of the entire bit of code.

98

u/DragonFireCK Mar 01 '21

Such optimizations are a lot rarer with strings (or any custom type), unless the comparison function gets inlined.

Additionally, as this is JS, its vastly less likely the JIT will optimize it out - newer JS engines have quite a few optimizations, but they are often still very far shy of what precompiled languages do, mostly due to the overhead of optimizing code that only gets run once.

37

u/JuhaJGam3R Mar 01 '21

oh god didn't notice it was JS

... maybe they have an optimizing precompiler to compress it? maybe? please?

21

u/bnz_ Mar 01 '21

Actually it's typescript, but i'm not sure that the compiled js have this kind of optimization. At least I hope so

21

u/Pangocciolo Mar 01 '21

So you have legacy code in a language born only 8 years ago.

The industry really needs to redefine the meaning of "legacy".

17

u/jayson4twenty Mar 01 '21 edited Mar 01 '21

Legacy to me is 12 year old Delphi code no-one dares upgrade or change.

This isn't legacy, it's just bad code people don't want [or know how] to change. Lol

Edited

7

u/bnz_ Mar 01 '21

Yeah it's not really a legacy code, but like a legacy code we poor young developers are not allowed to make any change because the seniors are scared af to broke something... Once I made a bit of refactoring of a super poorly written code and this was immediately discarded without looking at what I made. Sooo yep, best I can do is to post here to have fun and find another job

2

u/Pangocciolo Mar 03 '21

This is an opinion I agree with.

8

u/seventyeightist shameless Mar 01 '21

So you have legacy code in a language born only 8 years ago.

The industry really needs to redefine the meaning of "legacy".

Mmm I am not sure about that. The faster moving the language, the faster the transition to 'legacy'; what do you define the meaning of "legacy" as? (There are two types of answers here: those invoking the lifespan of the language, and those invoking the lifespan of the OG programmers!)

4

u/blindeenlightz Mar 01 '21

I see the "definition" of legacy code come up on stackoverflow from time to time. It's interesting how so many people have a different definition of it. Even the Wikipedia article on it has like 6 different interpretations of what it means for code to be legacy code.

6

u/Elsolar Mar 01 '21

I'm pretty sure JS should be able to optimize these kinds of redundant comparisons on strings, since strings are built-in and the language treats them as immutable values. The only thing in this code that I can think of that might obstruct the optimization is using == instead of ===, since (a == "") expands to something more like (a === "" || a === false || a === 0 || a === [] || ...). But in the abstract, IIRC JS runtimes intern all strings into a hash table and use the hashes of the string for constant-time equality comparison. So it's not like they're using strcmp under the hood or something. I can't think of any reason why a statement like (a === "" && a !== "foo") couldn't be statically optimized into (a === "") by a good JS implementation.

1

u/cube2kids Mar 01 '21

I'm almost sure that python has a lot of optimizations like these, and it's likely that it's the same for JS

6

u/DragonFireCK Mar 01 '21

I just tested on CPython 3.7.0 with -O and it lacks this optimization:

<redactedpath>python -O
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def test(a):
...     return a == 0 and a != 1
...
>>> import dis
>>> dis.dis(test)
  2           0 LOAD_FAST                0 (a)
              2 LOAD_CONST               1 (0)
              4 COMPARE_OP               2 (==)
              6 JUMP_IF_FALSE_OR_POP    14
              8 LOAD_FAST                0 (a)
             10 LOAD_CONST               2 (1)
             12 COMPARE_OP               3 (!=)
        >>   14 RETURN_VALUE

Its short circuited if the == passes, but if it fails, it still runs the !=.

Python's optimizations are not type-specific, and not doing this optimization is actually required due to custom comparers as well as floats due to NAN's odd behavior.

Javascript gets a lot harder as there is no true standard implementation: AFAIK, there are 5-6 versions in common usage.

2

u/Elsolar Mar 01 '21 edited Mar 01 '21

This disassembly is for the Python bytecode though, right? You'll have to forgive my ignorance of the Python ecosystem, but isn't it possible that this disassembly is missing optimizations that the runtime can't perform until it links this code against all the other bytecode used by the process? Generally speaking, I expect bytecode to be significantly higher-level than the final compiled output run by the VM.

Edit: I've done some reading, and I think I understand what you're saying a bit better now. The compiler has no idea what type a is of, and so it can't make the obvious optimizations. After all, a could be some crazy custom class with __eq__ and __ne__ defined such that (a == 0) is true and (a != 1) is false. More generally, the compiler can't statically assume that the == and != run without side-effects, making it effectively impossible to elide them. So my original comments about this being a case of compile-time optimization vs. link-time optimization probably is not relevant here.

I will note, however, that IMO this kind of optimization is probably much more likely to work in JavaScript than in Python, since JavaScript does not allow any custom equality or inequality operators (i.e., === and !== are not customizable at all). Strict comparison in JS is an identity comparison (basically checking if the pointers are equal under the hood) for custom objects, and for the built-in types they'll obviously design the === and !== operators such that our normal assumptions about boolean logic hold.

2

u/DragonFireCK Mar 01 '21

CPython (the standard implementation) operates by stepping through the bytecode in the same way the CPU steps through machine code. It does not do any additional optimizations once the bytecode has been generated.

There are other Python implementations that will end up with more optimizations, with some of the notable ones being:

  • PyPy runs the code though a JIT to produce machine code, I think bypassing CPython's bytecode.

  • IronPython compiles it into .NET bytecode (rather than the CPython bytecode) which is then run though the .NET JIT to produce machine code.

  • Jython, if I understand correctly, does the same as IronPython but with Java instead of .NET.

1

u/Elsolar Mar 01 '21

Thanks for the reply. I edited my original comment before getting a chance to read this, so sorry if that causes any confusion.

My original point about delaying these optimizations was meant more as a reference to compile-time vs link-time optimizations, but of course, for a JIT'd language that allows code to be added at runtime, the difference between a link-time optimization and a JIT optimization is somewhat academic.

I'd be curious if a compiler like Cython, which produces a native binary, would be more able to make an optimization like this, since it works more like a traditional static compiler. If the compiler can infer that (a == 0 && a != 1) is only used in contexts where a is a standard built-in number, then it can optimize more aggressively. It would work similarly to de-virtualization in C++, I think. I imagine even JIT implementations could do static optimizations like this in cases where the type of a is easy to infer.

1

u/DragonFireCK Mar 01 '21

A JIT can do such optimizations if programmed that way.

In fact, a JIT can theoretically do a bunch that would generally be impractical for a static compiler to do, such as making different versions of the function based on the runtime type of `a`, though the practical benefits of it are normally not worth the costs, both at runtime and in writing the JIT.

Its also worth noting that JS probably could not do that for numbers as numbers in JS are defined as being IEEE doubles which have NAN and the odd behaviors that entails. It should be able to do so for strings if implemented (string interning means string compares are just pointer compares).

5

u/ywBBxNqW Mar 01 '21

Maybe the wasted cycles being referred to are the people wasting "cycles" trying to determine if they can bother or should be bothered by it.

2

u/MatthewRPG576 Mar 01 '21

I don't get the first optimization

3

u/JuhaJGam3R Mar 01 '21

as long as c1 != c2, x == c1 implies that x != c2. If x isn't the first constant, and the first and second constants aren't the same, there's no way x could be the second constant. The second part will always evaluate true when the first is, so you don't need to do that check.

EDIT: no wait you probably would have got it fine without the explanation had i not mistyped 1 into 2. sorry

1

u/MatthewRPG576 Mar 01 '21

I'm guessing this doesn't work with operator overloadings that chenge the state of the variables they are comparing

2

u/JuhaJGam3R Mar 01 '21

th... huh? operator overloadings which change state? operator overloadings do not change state, especially comparison operators, otherwise they would be useless. if there is a language out there that allows you to overload == to change state i will actually lose all faith in humanity. i kind of get ++ and += and the likes but i really don't get why any other operator could be overloaded to change the states of its operands.

1

u/HelloStrangerBro Mar 01 '21

In other words: ugly and unreadable, but not less performant s as after compilation :)

1

u/schrdingers_squirrel Mar 02 '21

Even if it doesn’t it will be lazy evaluated and still not waste any cpu time.

1

u/sneakykenny Mar 02 '21

Wait in the second case if c1 == c2 then it shouldn't get turned to false

2

u/JuhaJGam3R Mar 02 '21

In that case. Since they are constants, c1 and c2 can be assumed to be different just because of how they're named.

68

u/TheBrainStone Mar 01 '21

I was wondering what’s so bad about this until I noticed the first condition.

24

u/bnz_ Mar 01 '21

In fact it was a stroke of luck that I noticed

91

u/Willinton06 Mar 01 '21

That’s a quantum string bro, it could be 2 languages at the same time so checking is a must

45

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Mar 01 '21

Image Transcription: Code


let saveLanguage = false;
if (languagesVal == "" && languagesVal != "en-US" && languagesVal != "it-IT" && languagesVal != "fr-FR"
&& languagesVal != "es-ES" && languagesVal != "pt-PT" && languagesVal != "de-DE" && languagesVal != "ru-RU") {
    languagesVal = "en-US";
    saveLanguage = true;
}

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!

15

u/BenjaminGeiger Mar 01 '21

Good human.

20

u/VoilaLaViola Mar 01 '21

Typical Debug-Driven-Development.

Someone at that line must have found languagesval to be "" and added another condition, not even trying to read (or even worse: to understand) the surrounding code...

16

u/seventyeightist shameless Mar 01 '21 edited Mar 01 '21

I took it at face value this morning, chuckled to myself and thought "hope I never do that!", but then came back to it later (because my partner is also a software engineer, as am I, and he was having a bad day with "broke the build" so I sent him this in the sense of "at least you don't have to deal with this"...!)

What struck me is the name of the variable, not that we should ever take any notice of that in itself obviously, but note it is the plural "languages" rather than "language", like they are expecting an array, set or some other 'collection'-type... so you can say the first "and" should have been "or" (although it would be redundant anyway in that case) but it seems more likely that in some precursor to this, either languagesVal was empty or it could contain some set of (1 or more) languages, and this is a poor translation from "if languagesVal is empty or it doesn't contain any one of en-US, it-IT, fr-FR etc etc" then default to en-US".

New hobby identified: supplying a superficially plausible backstory to examples on r/badcode. I am the kind of person to generate 69,420 possibilities of things per day so I'm sure I can accommodate this!

6

u/Kabitu Mar 01 '21

Always better to wear your condoms two at a time

3

u/bonedangle Mar 01 '21

Sometimes I have to ask myself what the inverse would be when looking at an expression. I found that helpful in making a decision on refactoring..

But in this case it's a basic lack of understanding values and simple logic 😂

5

u/DogsOnWeed Mar 01 '21

Either stick the language codes in a list and iterate through it as you check using a function, or put them in a switch statement, which despite looking better than if if if if if, probably takes just as long to write.

2

u/in-some-other-way Mar 02 '21

Read the first condition

1

u/DogsOnWeed Mar 02 '21

It's bugged I know, but even if it worked properly it's still a very tedious way of doing it.

1

u/RavynousHunter Mar 01 '21

At least have a damn speck of mercy and format the damned if, if you're hell bent on using the bloody thing over a switch! Or whatever Javascript's equivalent to Python's "x not in y" happens to be.

1

u/_Screw_The_Rules_ Mar 02 '21

So would a set/list of languages, that needs to be checked for the current language, be the best way to go about this or is there something even more smooth/faster/better?

2

u/path411 Mar 02 '21

Yeah, if you need to make multiple simple equality checks vs the same variable, just create a list and check if the list contains the variable.

1

u/_Screw_The_Rules_ Mar 02 '21

Okay thanks c:

1

u/lifeRunsOnCod3 Mar 01 '21

In python, this check can be achieved by creating a Set of the Permitted Languages and then checking if the language at runtime is a member of the set.

26

u/Willinton06 Mar 01 '21

I’m pretty sure you can do that in most languages

1

u/lifeRunsOnCod3 Mar 01 '21

Yes sure. I was just giving an example.

5

u/byornski Mar 01 '21

It's worse than that though due to the first check being == "". Excluding type-weirdness, the only way this can be true is if the other cases are also true so those tests are redundant.

4

u/SuperKatzilla Mar 01 '21 edited Mar 01 '21

Yep. langs.indexOf(currLang)==-1 in js. Edit: triple ticks to single ticks

4

u/AutoModerator Mar 01 '21

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/SuperKatzilla, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/Poddster Mar 02 '21

In python you can just check that languagesVal == ""

-12

u/IOException_notfound Mar 01 '21

For loops? I don't know what this is!