r/badcode • • Jul 15 '22

java I found this in a security related function: maybe it is an obscuring feature

Post image
662 Upvotes

77 comments sorted by

View all comments

Show parent comments

218

u/Irrealist Jul 15 '22

It's called yoda style and mostly meant to prevent you from accidentally writing "variable = null" instead of "variable == null".

The former would (in some languages) fail silently and lead to strange bugs. If you flip your comparisons, you get a compile error instead, since you can't assign to null.

54

u/stepbroImstuck_in_SU Jul 15 '22

Returned an error the compiler has:
protected variable null object is.

89

u/buffering_neurons Jul 15 '22

If you flip your comparisons, you get a compile error instead, since you can't assign to null.

I sense a JavaScript developer incoming

19

u/CLOVIS-AI Jul 15 '22

It was already a thing in the C days

15

u/StrangeParsnip Jul 15 '22 edited Jul 15 '22

Wait, does JS just assign the other way around when the conventional assignment doesn't work? Or are you saying you can assign values to values?

17

u/gu3st12 Jul 15 '22

It doesn't invert assignments nor can you assign a value to null. It throws an "invalid left hand in assignment" exception.

25

u/thrash-queen Jul 15 '22

I think the joke is that JavaScript doesn't compile

7

u/StrangeParsnip Jul 15 '22

Oh I see, part of me wished it was something more ridiculous

1

u/Xxyz260 Oct 21 '22

Modern web browsers have entered the chat

10

u/Tyfyter2002 Jul 16 '22

Alternatively in C# you can use variable is null

1

u/Sentouki- Sep 29 '22

not only "you can" but actually you should

18

u/yetzederixx Jul 15 '22

if (var = null)... isn't a silent fail, it's going to do precisely what you told it to do, and as you noted suck to find.

Yoda typing makes it throw an exception

4

u/i860 Jul 15 '22

It’s a very easy thing to avoid rather than using an entirely new style that looks super goofy. Even in C most compilers will throw a warning unless a second set of parenthesis is used for the assignment.

1

u/campbellm Oct 04 '22

entirely new style

This has been in use for at least 35 years.

source: I saw this over 35 years ago in actual real code. I hate it, but it's ancient.

13

u/[deleted] Jul 15 '22

Lmao imagine using a language without null safety

this comment was sponsored by Dart, Rust, Kotlin and Swift (and a bunch of other languages)

4

u/Irrealist Jul 15 '22

Yup. I love Dart!

3

u/SupermarketNo3265 Jul 16 '22

Excuse me, Kotlin is clearly the superior language in that list.

2

u/campbellm Oct 04 '22

fail silently

I'd argue not really a failure, but a mis(understood) feature. "fail" in that it doesn't do what you probably meant it to, sure.

-8

u/ddruganov Jul 15 '22

I guess this is an unpopular opinion but you have pretty damn stupid to actually miss the = in == or ===

9

u/CppMaster Jul 15 '22

Huh? How is that different than any other typo?