You forgot to mentioned that it's also awkward/unnatural to read.
All modern compiles throw warnings if '=' is used in 'if' statements. So, I'd say that there is no real advantage of using Yoda notation anymore.
We don't live in the 90s anymore 😉.
not really , I've used CodeBlocks for a while and this mistake killed me many times and it takes a long time to notice
@@AlaaAreesPhoenix I'm unsure whether code blocks is a very modern IDE that leverages the LSP or not
Let’s be real, if you have the awareness to think about the order, you aren’t gonna forget a double equal sign
Interesting, so people just discovered Yoda notation to hide their ADHD?
I think it is not about forgetting what the operators are, but rather about missing a key stroke and not noticing. Since the operators look so similar, this can be a bit hard to spot later
@@gruzuff9080 I dunno. Maybe if you're programming in notepad. There's no way an ide wouldn't catch the mistake.
@@DT-hb3zu In some programming languages assigning to a variable in an if statement is allowed. I think php and js both allow for this.
I also find it easier to read in certain cases such as: `if( 0 < very.long.expression) { ... }` because your eyes are drawn more to the beginning of the if statement.
Classic programming "improvements": shooting yourself in the foot by making code harder to read to prevent an error with occurrance rate of 0.001%
It's a bit more common than that, but there are solutions that are a LOT better than this, namely IDEs and compilers
@@draco5991rep I guess it might be like Javascript where == actually does type conversions meaning "42" == 42 is true while "42" === 42 is false.
I've been programming for 20 years, I can count the number of times I've mistakenly put a single equals sign instead of two on one hand. This is a solution for a problem that really doesn't exist.
Especially nowadays where IDE's will give you warnings about this exact kind of thing if you let it.
It's a cool idea, but I think it allows for someone to become more reliant on the compiler to spot the error and increases the chance that you won't notice "if (varA = varB)" because you come to expect an error for accidental assignment.
@@NovaHorizon You know how it is, there's just no pleasing programmers. Give us a good IDE and suddenly you're propping up bad programming habits; the only "real" way to do it is running Vim on Arch, with linker errors up the wazoo.
Fortunately, modern programming languages are pretty good at enforcing a minimum level of code quality by design. You don't need to worry about bizarre errors because the language doesn't permit them, and there are language constructs that remove the need for confusing code.
I'm pretty sure any decent IDE will yell at you if you do that. Or most languages don't even allow it.
And if you use any kind of static analysis tools, you will also catch the mistake. There's no excuse for using Yoda.
sadly mine does not tell me anything and I have spent waaaay too much time fixing glitches like this because I constantly forget
val = 42 returns true, which is a valid input for an if statement. This is not a syntax error, but a good linter might catch it.
Imagine you're speeding in a car. You've been pulled by a police officer and he's saying: "100mph is less than the speed of your car". Are you comfortable with that?
Amazing drunk driving test 😂. Im now startled, confused and wondering if less than means good in this context
It would be even weirder if he tried to assign a speed limit to you, which is why yoda notation exists.
@@gencurrent incorrect. You chose an inequality. Yoda is to prevent accidental assignment which is not an issue for inequalities
if a junior programmer is unknowingly writing an assignment instead of boolean comparison, they definitely won’t be writing code like this to prevent the error in the first place
mistyping is not a junior problem.
Anyone with an iq of over 90 can be taught which side of the equals the variable should be on. I agree, if we contionue to not teach this, an inexperienced programmer would not. But this seems like something we should just start teaching in highschool programming. This is the sort fo thing Rust for example could jsutn throw an error if you were not doing.
Oh, so you never make typos eh? Never make mistakes? I've known the difference for a good ten years. This year I made this exact mistake once or twice.
to everyone who says that the compiler will warn you about this, thats assuming you pay attention to warnings in the first place. Tons of codebases have all kinds of detritus coming out of the compiler that gets ignored. Or a 10+ minute build where you get up and go for coffee, you aren't going to see the compiler warning.
In Java, “str”.equals(str) is also better than str.equals(“str”) because it avoids NullPointerException
To make it more beautiful just use a constant: Constants.MY_EXPECTED_VALUE.equals(str)
How i code:
- Attempts to code
- nothing's working
- go to internet
- realize I'm an idiot
- fix code with the answer to a question someone asked on Reddit / quora 10 years ago
- code works until problem happens again.
[I live in endless pain :)]
Strict syntax rules in languages such as Java, Scala, and Rust can prevent certain errors, while Yoda code may appear unnatural. Also using linters, static analyzers, and tests can help to identify and prevent such issues in code. It's worth noting that in the past, in languages such as Fortran, it was possible to assign values to constants, which would lead to unpredictable behavior with Yoda code.
Fortran seems to have an interesting interpretation of the word "constant"
Yoda Programming is popular in java. Since you often have to call functions in these if statements and calling functions on null causes a runtime exception, by putting your constant on the left side, you eliminate the chance of null-pointer exceptions.
I've only found Yoda notation good for one thing: comparing a constant with a nullable value. If you do `myvar.equals("string")` and `myvar` is null, you get a NullPointerException, but you don't if you do it the other way around.
Not that I didn't believe you but i had to try it for myself. Pretty nice. This could certainly be useful in specific use cases. Thanks.
I do have one instance where this can be helpful: checking if a value falls within a range. Using Yoda notation for the first comparison makes the read order match the mathematical notation:
if (2 < x && x < 8) {…}
In all my years in software I've never ever encountered this error. Just add good test cases and you're good
I'm going on 10 years as a professional developer and I've not seen a codebase that follows a test process in a meaningful way to catch this.
@@LuckieLordie Really? two test cases, one val == 42 and expects puts("42") another val != 42 and asserts puts("42") isn't called. The second test case should fail
@@Nominal_GDP Unfortunately, these days, general/basic coding skills have gone south since critical thinking, for waay too many, has been offloaded to stackoverflow/google. Additionally, while confusing = and == shouldn't happen, there's always a risk it will...languages should never have been designed with this kind of (anti-intuitive) risk in the first place.
Compilers (such as gcc) and stagic analysis will warn about this - this style is obsolete.
@@zz-ox7ud I agree with you, but it's often easier for developers to turn off the warnings than it is to read and understand them. I wrestle every day with developers who tell me they need to release today rather than update a dependency or fix some line in order to get something released.
SDLC just isn't a priority for many developers and the few who understand it just don't care enough to delay something to get it right.
Fun fact. In safety critical applications, like automotive and control systems, "yoda-notation" is mandatory, and in fact it is part of certain safety-focused coding standards like MISRA-C
Yes, but you will probably also use something for static code analysis in such projects.
This is true if you write code with notepad++. Otherwise any decent IDE is able to give you a warning or notice.
I don't code like either of these, 42 is a magic number, store it somewhere.
@@isaacbruner65 Or store it somewhere AND explain it in a comment.
That number is the answer given by a supercomputer to “the Ultimate Question of Life, the Universe, and Everything. You really need that explained in a comment? smh
@@johnc3403 Well, we need the right question to understand the answer. We are still waiting for that.
Or just don't forget a double equal sign when writing a boolean expression
In most modern languages the compiler usually doesn't allow assignment operations in a conditional statement, i.e. inside round brackets of an if..then statement
Not exactly true, at least not if you're doing perl5... you can compare and iterate inside an if statement.
++$i == 5 will add one to $i before comparing $i++ will compare existing value and add one after ... it's a nightmare to read for someone with less experience, and many IDEs will warn you about it, but it's still a perfectly valid way of saving 1-2 lines of code, especially when you're doing a for loop or a case condition.
But dont you have it backwards. It sounds like these modern languages realised the danger of this type of expression. Yoda solves the danger and leaves the good aspects and freedom, these modern languages just disallowed the whole thing removing a really good way of simplifying and shortening your code.
it's all about whether assignment is statement or expression. if the latter, you (as a language) automatically have to allow it inside if (and while) in order to be consistent. you also get multiple assignment like a=b=c; for free
C is modern for what it does. You can't escape writing low level programming languages if you want to move away from building todo apps
That's a solution worse than the problem. It would be better to require a AND I MEAN it to validate it than forbid a useful mechanic.
And this is why you usually want assignment to be a statement and not an expression, because then either way you would get a syntax error to help you quickly remove the typo.
I'm seeing a lot of hate for this harmless trick and I have no idea why
You will notice this, when you write more code. The fun really starts when greater-than or less-than operations are involved. It just doesn't read natural and requires additional attention from the programmer. Thus, draining cognitive bandwidth which would be put to better use to keep the overall overview of your project. It is hard for a tool to catch big architectural mistakes. This is something a human would mostly have to take care of. However, tools can very easily catch such low-level mistakes. So don't waste human brains on low-level stuff. Just cover it with tooling, so that human brains can be used to cover the more abstract things such as architecture and actually reaching the desired functionality of the code.
Because is akward to read an unintuitive.
And avoiding all assignemments inside if statements is usually a better solution.
It's not harmless when you come to rely on it to catch erroneous assignments - and then compare variables.
Mostly people who have never touched C or critical SW complaining that they're too stupid to understand that code isn't always evaluated left to right. Or they don't understand that nobody advocates for yoda notation in languages where yoda notation doesn't protect anything.
I'd rather have a linter catch this than difficult to read code.
Been watching for 30 minutes. When does the video end?
The End is Never The End is Never The End is Never The End is Never The End is Never The End is Never The End is Never The End is Never The End is Never The End is Never The End is Never The End is Never The End is Never The End is Never The End is Never The End is Never The End is Never The End is Never The End is Never...
I have seen this notation in lot of places and wondered what could be the reason. Thanks for the explanation
There was a time when compilers would balk and crash to desktop with Yoda speech.
The solution is not Yoda notation, the solution is to avoid C
I first encountered this syntax type in my career back in the early 2000's. Programmer did so for reasons stated in the video. People need to understand that IDEs in the 90's were quite primitive to what we have today. Heck, I remember when syntax highlighting was introduced to VS and what a big deal it was.
@@Brahvim I am thankful many IDE can catch simple typos such as a missing semicolons without having to run the compiler first. Makes programming far more accessible.
The last I heard, you can tell gcc that you intended to use an assignment by wrapping it in extra parentheses: if ((i = 42)). It also visually signals to others that it was your intention to write that mess - it was no accident.
The more evil version:
i[array]
(Reversing index and array prevents calling an overloaded operator[] in C++.)
Am I crazy or did nothing change between "you" and "yoda"
Where I worked at back in the 1990's this was a requirement for all our C and later C++ code. I haven't seen it used much lately. In fact we had a server that would check nightly for all code that was checked into CVS and search for this and flag the code as unsafe and email you. Our C coding guide was fairly detailed. at over 100 pages of coding suggestions and even rules such as outlawing the question mark operator. There was a list of "safe" functions that replaced or wrapped many of the unsafe c standard library. Others were rules to look at such as make checking structs to make sure they were byte padded.
Not bad guidelines, the ? Operator is interesting and looks cool sometimes ...but not at all necessary
why were you guys specifically checking for explicit byte padding? its well defined by ABI on x86 and arm.
Some nonstandard compiler?
In the 90s this was justified more or less. However, if you have a linter checking for yoda code, then why not using "normal" notation and use the linter to catch a single equal sign?
If you code wrong, you're coding wrong. But if you code in a way that is harder to read, you can prevent a dumb mistake that you would catch anyway? The worst part is that chatgpt will pick this up and implement as "best practice" just because a dozen rando youtubers decided to sh*t out boring content..
You wouldn't necessarily catch the mistake in a large program. It could cause a lot of unnecessary headache debugging, even if you eventually do figure out the mistake.
@@bsykesbeats I feel like a lot of people in here saying "just code correctly and don't make mistakes like this" haven't actually done any serious coding lol.
@@Redman8086I have. Compilers have warnings for this for twenty years. I remember this tip from the 80s and I found it so unreadable that I discounted it immediately. I don't recall ever making this mistake.
I've learned this in small company and then my code was rejected during CW at Uber. Now I never use it, really akward
As an pythoner, python simply raises error in both cases.
I’ve seen some programmers that code like this but personally I don’t like it.
It makes it way more unnatural to read and I’ve never had a problem with accidentally doing =
You have to do this with strings in Java, unless you want to be called up in the middle of the night
No you don't. There's very rare valid instances of needing to check for null strings within business logic... in most cases what should be done (and isn't being done) is ruling out nulls at your input stage, and then in your logic just confidently write your expression the way you meant to. Yoda conditions are awful and make code harder to read for no reason. People just constantly patching symptoms instead of treating root causes is why I hated working with java professionally... it's easy to learn and any moron who wants to make a buck in consulting will half learn it in a weekend.
Just write code the way you mean to, and explicitly write null checks where they're needed. It's not null checks that will make a difference in your performance, especially when you're already allocating millions of objects every second to perform the simplest of tasks in whatever framework is used these days.
@@LordFokas Ever since I worked with someone else function that returned the string "Null" I will never trust anything, let alone trust that in input stage prevented something from happening.
@@shawnsustrich7981 becoming part of the problem doesn't make stupid patchwork more reasonable.
or you just uhhh
use exception handling and catch a NPE like everyone else
@@DarmaniLink if you need to catch an NPE you're doing it wrong. Some of the worst bugs I've had to deal with were caused by juniors thinking they were smart catching NPEs instead of validating inputs.
Haha, no such problems in VB. 😉
Visual studio gives a warning for this, making it nearly impossible to do by accident. I'm sure nearly every other ide on the planet will have some option to flag this.
Okay, this is genius and will be doing it from now on. Thank you for your service. 🎉🎉🎉
experienced programmers compare with a constant rather than just a number to avoid an antipattern named "magic number"
Spoken like it were 1985.
that's actually really handy, i never thought about switching it
Interesting, this notation is
Or, work in an environment that just tells you...because it can.
For literals this can be great, but what is both sides have a variable?
This is why colon equals was a better notation for the assignment operator, so that you don't accidentally assign a variable in a conditional statement.
This is useless. Never use magical constants in your code. Sure, the left value might be a named constant, but a lot of times I still need to compare two non-constant variables. So what is the point of making a rule that doesn't help in a lot of situations?
This is mentioned in Code Complete. (Steve McConnel)
Why does "if (val = 42)" even work in the first place?
also yoda notation is prohibited by most style guides
youtube randomly recommended this short, i didn't understand a single word, 10/10 would watch again
Yoda syntax is a symptom of patching a failure of the language with a bandaid. Instead, just fix the language.
Simple. Don't allow assignments in conditional statements. Modern C compilers will warn, but not prevent it. Warnings are an OK compromise.@@DK-me8iy
@@DK-me8iy They did fix it by creating a brand new language out of C. It's called Python.
I made that mistake once in collage. Yoda notation, I've used ever since.
I once spent a week on a side project because of this very error-
Doesn't work when comparing two variables, which is way more likely than comparing to a literal.
Ah, I see your problem. You're coding in a pre-modern programming language. Have you tried Ada? Or Component Pascal?
This is not only an extremely minute problem, it's not even a problem in some languages. In Python, assignment is not an expression (ignoring the walrus operator for bit) and you'll get an error. In Rust, assignment always resolves to unit, which is not a boolean and therefore isn't allowed as an if conditional.
Or use a linter
@@somusz159 That’s even funnier to read. We’ve been using ML models to do that job for half a decade already. GCC is the only compiler not already doing this.
I don't like it myself, but I wouldn't reject a code review because of it
Accepted with comment "Please apply automatic code styling before merging"
Luckily, in python it yells at you if you forget the second =
Well, this works great when you go around hardcoding constants everywhere. As soon as you use variables though, this wont work
You likely have linting rules to prevent this
I think it's unneccesary, but it's not any harder to read.
Just get a decent linter. Should catch mistakes like this automatically.
love that, we have a specific linter that hits person's head when he/she writes code in yoda statements
who tf forgets the other equal sign? twelve year old python guys?
Dude I' ve seen this notation in a repo weeks ago and I was thinking the dev did like this to be faster reading. Using your example, you dont need to seek with your eyes till the end of the line to undeerstand what it is being compared to. Very nice
just to be clear, it really can be confusing with "int statements", but if you are talking about string or boolean comparisons, i think it can be really helpful
You could also say it's programming in the passive voice xD
In my 15 years of coding never did I make an error of this sort, nor saw someone else making it.
Guys, we get that modern IDEs with AI-powered code prediction can detect this stuff and throw 800 warnings in your face. But the channel is LOW LEVEL LEARNING. Low level at some circumstances means you're gonna be looking at some raw code, in embedded platforms, where you being able to see the text is already a miracle.
Your argument is much more convincing than that other guy who was just calling people soy devs instead.
That doesnt happen in Python
You need to make a full series on good practices
Every compiler has added checking for this decades ago and it works even when both parameters have an lvalue. Yoda coding in the 21st century is a red flag that the author either doesn't know about compiler warnings or has disabled them because their code is broken.
This is so cool! I'll definitely start doing this!
Also, in object oriented languages, (i.e Java), yoda comparisons are actually a better practice for checking values against constant. I.e `userRole.equals("user")` could throw a NullPointerException if something ever causes userRole to be null. Whereas, if you do `"user".equals(userRole)`, you'll automatically be null safe. Obviously the best solution is to address the source of that null, but sometimes that's easier said than done.
Unless the code runs something that is CRITICAL, I'd rather have a null pointer exception to debug than not ever realizing there was a null somewhere that wasnt expected and get other harder-to-trace bugs to fix.
If this is the type of shit you think will make you a "better programmer", I feel sorry for you
Using yoda notation is actually important in Powershell when doing null checks. The equals and not equals operator actually have the ability to return values when used with arrays. Therefore its possible to get unintended behavior if null is on the right side.
It’s just that ‘val = 42’ returns true because because the variable ‘val’ managed to be assigned to 42 so no matter which variable assignment you put in the if condition, the code inside of the if section will be executed
This is a problem that can be solved by just configuring a linter.
I feel like this is way harder to remember rather than just remembering how to do it properly
Dude, this is such a useful trick, thanks a lot.
Also, the expression resolves to "true" because "val" can actually accept the number "42" as it is an "int" variable, so the if statement will always work. Thus it's not really an if statement without the double equals.
But if I want it to go into the block only if (and only if) ret is exactly 42?
It's also useful to prevent NPE in java, like "Something".equals(input) will just be false if input is null. But input.equals("Something") will throw NPE.
This is actually a good tip because this kind of error cost me hours of debugging
Meanwhile junior developer using a pattern matching functional language : I’m about to end this yoda’s whole career
I’ve had devs tell me it’s hard for them to read, and that’s enough to stop me from using this
I was always wandering who the fuck is coding like this. Okay, now I know the answer. Makes sense but it just looks so wrong
Yoda notation is genuinely useful when trying to avoid null pointer exceptions in languages like Java.
The following code throws an error because the variable s is null:
String s;
boolean isHello = s.equals("Hello"); // NullPointerException!
If you use Yoda notation, no error:
String s;
boolean isHello = "Hello".equals(s); // false
IMO this is nicer than writing explicit null checks every time
It is a clever way of making code more reliable without making it complexer. I like it and will use it as a computer engineer.
I've always written it in a more semantic way based on which value is of more interest or meaning. In other words, "do I want to know of THIS is equal to THAT?" or "do I want to know if THAT is equal to THIS?". But I like the reasoning in this video even more maybe.
some languages will throw warnings if you use a single = in an if statement, but some further simply do not let you make assignments in if statements _at all._ personally i think that's much better, any assignment you could do in your if you could do before or inside it
I have no idea if this is common practice, but another potential use for Yoda coding is if in an SQL statement you want to filter for a value in any one of several columns, you can write something like:
*_WHERE value IN (col_a, col_b)_*
I haven't measured whether there's any impact on performance, but it saves an *_OR_* clause or two.
You can instead set the compiler to treat the warning as an error and it won't compile in the case of the mistake while remaining easier to read.
In Java, there can still be an advantage:
In Java, == does, for everything that isn't a primitive (boolean/byte/short/int/long/float/double), reference equality, not object equality - for that, you'd use .equals(), which an object can also override for itself.
aStringThatMightBeNull.equals("bla") can cause an erro, "bla".equals(aStringThatMightBeNull) will just be false.
I was a big advocate for "Yoda notation" when I worked at EA years ago (though I've never heard it called that specifically). Used to get in fights with one of our style enforcers about it. I actually saw someone make the single-equals mistake and cost us weeks of debugging to find it, so there you go.
That is brilliant.
I've never had anyone justify it.
Yer, That was how they taught us to program in C. Back in the days when compilers didn't do a lot of lint checks & Yoda hadn't made it to the big screen.
I have no idea what is goin on 💀
Coding
Yo same.
Usually it’s perverts that think they’re perfect.
There's a variable named value and in your original code. If the value is equal to forty two stuff happens however a junior programmer says if the value is equal to forty two with only one equal sign.
In this instance the single = is not a comparison operator but in fact sets the value of vow = 42 which is always true because it's. Successfully completes the operation and then the next part of the code runs saying. Yeah but the thing passed the check
While speech your text mangled that but uh you get it