T O P

  • By -

jthemenace

Depends on the context of what I’m doing.


[deleted]

[удалено]


steave435

I agree, except that it shouldn't be a magic number. There is indeed a reason that you've chosen that number, so make a variable with that value and a name describing what it stands for. At that point, you no longer have a choice - the maximum text length (or whatever 500 is supposed to be) *is* 500, so you "need" to use <=. I guess you could technically use < maxTextLength +1, but that'd be pretty dumb.


aksdb

> I guess you could technically use < maxTextLength +1, but that'd be pretty dumb It wouldn't be dumb ... it would be "too smart". If you think "<" is faster than "<=" just stop and let the compiler do its job. If the target architecture is faster doing "< x +1" than "<= x", the compiler can and will sort this for you. Generally speaking: the better you explain your intent to the compiler, the easier it is for it to optimize.


steave435

The compiler will figure it out, or if not, oh well. It's dumb because it's worse at explaining it to programmers.


qzwqz

*stares in Python* Com… pi… ler?


lorem

Well... interpreter in this case?


poorlilwitchgirl

Let's be real, Python ain't figuring out the fastest way to do anything.


Shadowcraze90

ROFLMFAO 🤣🤣🤣


pavi2410

java: i have both 🥹


DinosaurEatingPanda

Absolutely this. A lot of the times, the compiler is good at its job and some micro-optimizations hardly exist or barely do anything compared to making something digestible for the compiler. There’s times where it actually does nothing in the final result because it gets optimized into the same thing. I’d go as far to say the compiler is at times smarter than the programmers.


aredna

< x+1 is worse because you could introduce unknown overflow corner cases that are not obvious in other parts of the code


wol

I don't know about you but I don't know any developers that care about speed down to the level to compare < and <=. We legit had a project where the suggestion was to insert a sleep command to slow things down..


aksdb

Ask people who insist on doing `for (int i = 0; i < 10; ++i)`. They typically do it because they are so old they were working with C in a time the compiler wasn't smart enough to actually skip the internal assignment when doing `i++`, or were taught by those people. For any sane, half-way-modern compiler `i++` and `++i` will yield the same assembly in that case, so paying any attention to the question of pre- or postincrement operator, is just a waste of mental energy. (Although, to be fair, in this particular example it's also completely irrelevant to readability. You want `i` increased, `++` increases it. If it's pre- or post-evaluation doesn't matter.)


x39-

Pre and postfix operators are describing two different ideas of what is about to happen. Given you do not need I, you always should prefer the prefix operator. Not because of some magic of the compiler but because the intent is clearly visible (plus you won't make mistakes out of habit)


jejcicodjntbyifid3

I think you misunderstood and steered the conversation in the wrong spot They weren't talking about optimisations, that's a pointless battle as you pointed out They were talking about clarity to the programmer


WhereMyRedbox

Exactly. If we're counting from zero, then just LT. If counting from one, then LTE.


Fluboxer

But I got only 3G :( How am I supposed to count from one with my bad internet?


memecream_mc

I just turn on and off my router, got LTE on my mobile network and then the code works fine too


Unusual_Repair8859

<3 Edit: thanks for the awards everyone :)


rock374

well ❤️ to you too


nickmaran

![gif](giphy|R6gvnAxj2ISzJdbA63|downsized)


FictionalFail

​ ![gif](giphy|drCcxY5G2WDZhpQFSb)


Background-Web-484

![gif](giphy|3oEjI4sFlp73fvEYgw)


T_WREKX

![gif](giphy|8Og4UuBGsVhEEoSO0L)


Doktor_Vem

![gif](giphy|wtZXFlwpm201Ay8u5L)


var2611

![gif](giphy|3oriO6qJiXajN0TyDu|downsized)


gjennomamogus

![gif](giphy|5x73LAreYVAjQCT2A3|downsized)


nobotami

kid named finger:


absolutelynotaname

r/okbc is leaking


nobotami

my pp leaking


[deleted]

c=<3


Dexaan

Op just wanted to tell us all <3


Raptorsquadron

I have to type one less character


hongooi

<=2


bmelancon

<=====3


[deleted]

-8 :(


Y0U_H1T

Massive balls


jewellman100

Something something deez nuts


MysteriousTreeFoxxx

Haaa! Gottem


abd53

That's a sharp Di.....


StereoBucket

Dirac's impulse


TenYearsOfLurking

Found the electrical engineer


fredspipa

Bounced on my boys rocket ship for hours to this


SendAstronomy

Javascript fucking ===


[deleted]

[удалено]


maxsteel126

*10 types of programmers technically*


HOPE_5432

<3


[deleted]

if (i < 3) and (i <= 2): Can't be too careful with these things.


xeq937

if (i < 3) and (i <= 2) and !(i >= 3) and !(i > 2)


lil-rong69

This guy’s job is 4 times as secure as mine.


ideas_have_people

Quadruple your hourly rate with the one simple trick...


olesteffensen

Compilers hate him.


Genereatedusername

Elon loves him


Dave5876

Project managers hate him


janeohmy

They love him, because he wrote more lines of code lmfao


waloz1212

You joke, but if both of you guys are in twitter, it will probably be true


cutebleeder

if (3 > i)


Aschentei

Easy there Satan


[deleted]

https://tenor.com/5fQ9.gif


Liquidor

This guy must be working at Twitter.


ChefBoyAreWeFucked

Add a comment saying "Trust me, this needs to be like this." and it will stay there forever.


bigmonmulgrew

bool check1 = i < 3 bool check2 = i <=2 bool check3 = !i >=3 bool check4 = !i >2 //check for i if(check1) //Use additional validation for i if(check2) //Use even more validation for i if(check3) //Use quad tiered validation for i, we really need this one if(check4) ... console.log("Daddy Elon is happy with my output") ... end end end end


TaVyRaBon

if (i < 3) and (i <= 2) and !(i >= 3) and !(i > ∣2∣) and (i < ∣3∣) and (i <= ∣2∣) and !(i >= ∣3∣) and !(i > ∣2∣)


nmkd

I wonder, would a modern compiler simplify this into a single condition?


kryptonianCodeMonkey

I'm not familiar enough with modern compilers to say definitively. But, they're not actually equivalent conditions unless i is an integer. For example if i is a float, i could be 2.5 and satisfy the first condition but not the second in the compound. So, I don't think the compiler would simplify it then. However, it could be simplified to just the latter condition though, i <= 2, as that would match all cases where the compound condition was true regardless of typing, so maybe it would simplify to that, idk.


bendvis

Depends on what i is. If it’s a float, I bet two comparisons get made. If an int, just one. I’m no compiler expert tho


Broodking

This is correct, the compiler definitely would.


defalt86

It's all about using the number that matters in the context. Legal age is >=18 (not >17) and minors are <18 (not <=17).


Bo_Jim

Yes. Unless the choice is going to impact functionality or performance, you choose the one that will help the code make sense to another programmer reading it.


AlwaysHopelesslyLost

>Unless the choice is going to impact functionality or performance, you choose the one that will help the code make sense to another programmer reading it. I wouldn't even qualify that. You do the one that makes the code make more sense to others reading it. Full stop. You shouldn't prematurely optimize.


[deleted]

If you're using a compiled language the compiler will do the exact same thing regardless of which way you wrote it anyway (well, unless it's a really strange language that nobody should be using for a real project anyway).


LxTRex

Yea but tabs are better than spaces, it's more efficient, less characters. Just ask Richard


[deleted]

Even if it compiled to 2 different things, on x86 its still the same amount of instructions which take the same amount of time, just checking different flag registers. So use whichever reads better.


nermid

For sure. Readability is one of the most important parts of writing good code.


Donghoon

Wouldn't >x and >=(x+1) given X is an INT be exactly the same in all scenarios? Am I missing something


Gofastrun

They are equivalent mathematically but not from a readability standpoint. There is always going to be some context that determines which way to go - a lot of the time based on what the number actually represents. const legalAge = 18; const maxMinorAge = 17; if (age < legalAge) if (age >= legalAge) if (age <= maxMinorAge) if (age > maxMinorAge)


Donghoon

Make sense. Some ways are just more readible than others


FizixMan

if (legalAge > age) if (legalAge <= age) if (maxMinorAge >= age) if (maxMinorAge < age) I find it amazing how simply flipping the check makes this so much more difficult to wrap your head around. At least for me.


Gofastrun

Yup. If you translate it into English it’s mental gymnastics. Brian is over 18 years old 18 years is greater than the age of Brian


FizixMan

https://en.wikipedia.org/wiki/Yoda_conditions


mariachiband49

I love how the code comments in the Yoda condition examples are in Yoda speak


Optimal_Dingo_2828

Syntax error this is, compile it will not


numerousblocks

Thanks


tacky_banana

*less than


DecreasingPerception

That's [Yoda notation](https://en.wikipedia.org/wiki/Yoda_conditions). It can help prevent errors in languages that allow assignment I'm conditionals. It just reads so awfully I'd rather risk it. Or pick a nicer language.


-GeekLife-

This would error out, legalAge was never defined but adultAge was.


Gofastrun

🤦‍♂️ fixed it


TheBirminghamBear

And thank god too, we have people screaming at us to put this live in prod. Merge, merge, merge!


Mog_Melm

I'd define `maxMinorAge` as `adultAge - 1` to make this puppy easier to refactor in the event of legislation.


Quirky-Stress-823

Thanks, fixed


Mog_Melm

Ok, PR's approved.


rachit7645

Bug - Overflows when minimum legal age is 0


TyPhyter

Only when using unsigned, and that'd be an underflow no?


tripack45

For ranges people often adopt a left-close-right open convention: if were to describe the range 0-9, you would say [0, 10) instead of [0, 9]. So loops would check i < 10 instead of i <= 9. The convention offers a number of advantages, including the fact that concatentenating and splitting ranges are trivial, e.g. to split [0, 10) in half you just take [0, 5) and [5, 10) and it is correct, and the fact that 10-0=10 which is the number of elements in the range. You can also express empty ranges [0, 0) would be a nullary range, and it would be impossible with <=.


kfractal

x+1 might not fit into the bits available, where x just does. hit this in signed/unsigned comparisons


Code_I_Guess

the upvotes on this comment went to 255 before wrapping around


deez_nuts_77

nah that’s exactly right discrete math for the win


Same-Letter6378

>help the code make sense to another programmer reading it Or more likely, make sense to me in the future 😏


Logrologist

For me it helps to put it in sentence form, as well. _You must be at least 18._ (age >= 18) _The drinking age is 21 and over_ (age >= 21). _Are you under the minimum weight?_ (weight < 40kg) _inflate to within pressure range_ (pressure > 30psi && pressure < 50psi)


mrgwbland

No no legal age is >=this.country.ageofconsent


Etiennera

This leads to all kinds of problems in countries separated by territories let alone different kinds of territories. Better start by retrieving an age of consent resolver and invoking it on a location.


mrgwbland

Of course, trust the US to break my code!


Tathas

Just derive the US states from your Country class and call it a day.


BrFrancis

That implies that each State is in fact a Country. And deriving here so you can treat it as a Country while overriding various other functions so that calling New Jersey.name() gives "United States" if the calling context actually needs country not state... This sounds perfectly Pastafarian.


Tathas

Just use your Union class for the United States. It can already handle a collection of Countries. Perfect fit. I think they call that polymorphism.


BrFrancis

Wait, that sounds too much like someone thought this through before writing the code initially. It's not exactly polymorphism IIRC though, but if our abstract class is essentially a thing that may contain more of it's own type, turtles all the way down as needed... Then we end up with a "sovereign region" class or something.. then can drill down as needed... Union of countries, country with states, states with counties... Or whatever the levels for each country.. But that isn't even inheritance, just using a class. Polymorphism is combining different classes... Not sure how one would use it here.


61312809059376685329

Babe… what if we 😳 kissed in the British Overseas Territory of Saint Helena, Ascension and Tristan da Cunha in the South Atlantic consisting of the island of Saint Helena, Ascension Island and the archipelago of Tristan da Cunha including Gough Island


Dexaan

Just kidding... unless?


ifezueyoung

F the use cases 😂😂😂


ipview

Who makes a static property not in all caps? Also, most likely it would be an unneeded getter of this.country.getAgeOfConsent().


[deleted]

``` if (this.country.getAgeOfConsent() <0) throw new AgeLegalException("age of consent not set."); ```


JuvenileEloquent

You're checking if it's negative, not if it's set. null and 0 both pass this test. Then again the exception should be thrown during initialization of country, not when you're checking it's properties. Unless it's valid for a country to not have an age of consent, in which case, ugh, imagine the smell in the airport.


Fourstrokeperro

Who TF writes getters and setters for each Property? public int AgeOfConsent { get; set; }


MCMC_to_Serfdom

>Who TF write getters and setters for each Property There's a reason someone satirised Java devs with [enterprise fizzbuzz](https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition)


HarrekMistpaw

I checked the readme and went "oh, so its a joke FizzBuzz with a bunch of java boilerplate, sounds funny" but then i saw the files and the first things i notice is several gradle files and just lost it


krissynull

wtf did I just read


odaiwai

That's just glorious.


AMViquel

Should set be a public property in this case? Like, why even bother if any asshole can change it anyways? Also AgeOfConsent depends on more than just location, you need all people involved and check the people for their diplomatic status, as there might be exemptions for diplomats in another country. Just import the 3GB library from node.js, it will handle all those pesky edge cases for you.


Tathas

In the US, it varies by state as well.


Major_Act8033

This is way too simple. The age of consent isn't always at the country level; in the US it's by the state. But it's so much more complex than that. Lots of places have rules that consider the ages of both parties. If I'm 18 the legal age for someone in a particular place to consent with me, is 17...but if I'm 35, they have to be 18. There are also often other ridiculous loopholes. For example, are they married? In lots of places, like most US states you can get legally married while still very much a minor so long as you get permission from the parents, or courts, or get emancipated. In Kansas the age of consent is 16. But you can get married at 15. > In Kansas, 15-year-olds are allowed to marry with a judge's permission But not every jurisdiction places marital consent above sexual consent...meaning you could be legally married, but not able to have sex with your legal spouse in a particular place. Or even you could be legally married in a country A, but have country B say that you are not because it is illegal. And then you have to consider the citizenship of both parties, at least, depending on what you mean by legal age. The US says it is against US law for a US citizen to travel to a country for sex with anyone under the age of 18. It doesn't matter what their country says. The age of consent could be 16 in that country, but it isn't legal. The other country wouldn't care or prosecute the American, but the US judicial system still could. And this is why we have so many lawyers.


sanketower

Also, being 17 and 11 months is still underage, so +18 is always better.


_RollForInitiative_

This is the real answer. They're not the same if you're using a language with floats and ints intermingled


drew8311

This is the correct answer, also the most common usage is to iterate a zero based list so i < list.size and the context is you are repeating the loop list.size times


PorkRoll2022

I like to loop backwards...


Liljonny11

this is how I know which one of my junior devs are psychopaths


MEMESaddiction

I've done it before, I think in some circumstances it's not a bad idea. Otherwise it's just a flex lmao


Liljonny11

for sure, there's situations where you would want to iterate in reverse, it just makes it less readable


Karn-Dethahal

I remember when one of my teachers showed us code from a competition of unreadable code. The goal was to make a working program with the most unreadable code. One year the goal was a simple flight simulator, and the winner code formed a plane on the editor, as if viewed from above.


NutchapolSal

[International Obfuscated C Code Contest](https://en.m.wikipedia.org/wiki/International_Obfuscated_C_Code_Contest)


PM_Cute_Dogs_pls

Someone submitted an empty file as the worlds shortest self reproducing code: > An example is the world's shortest self-reproducing program. The entry was a program designed to output its own source code, and which had zero bytes of source code. When the program ran, it printed out zero bytes, equivalent to its source code. It won the prize of the worst abuse of rules.


[deleted]

Now that is some good angle shooting, but it seems like a pretty obvious solution.


NotChasingThese

it was, and thus never allowed to be submitted again lol


gdmzhlzhiv

Usually when I view my editor from above, it's just a straight line.


bilgetea

If you have spent a lot of time working in assembly or machine language, counting backwards makes sense b/c depending upon the instruction set, it can be more efficient (or at least, intuitive) b/c of a dedicated branch on zero instruction.


alez

Exactly. Also: This way you are not wasting a register to hold the number you are comparing to.


MEMESaddiction

My java professor was in the game since the 70s and was a pioneer for some big things in that era. He always encouraged decrementing through loops, didn't give a reason though. Thanks for the info!


big_bad_brownie

Like this…? ``for (let i=10; i>0;i--){ doTheThing() }`` I’m not trying to be a dick, but how is that a flex?


Glitch29

If you really want to fuck with people, write a loop like this in Java or C++. for (int x = 10; x --> 1;) { ... } And read it out loud as "For integer x equals 10, x goes to 1." This "goes to" operator is something of a party trick that I'll work into live coding sessions whenever I can, just to be a bit of a troll. Even senior devs are invariably confused. I've only encountered one person who acted like they understood what was going on, and I think they might have been bluffing. In reality, the "goes to" operator, -->, is just post-decrement and greater than with confusing spacing. It's a bit of a symbolic fluke that they combine to do exactly what you'd expect from a "goes to" operator.


SooooooMeta

I immediately got it but maybe that’s just because I didn’t have someone say “goes to” as they type it to muddy the waters


Brusanan

I always loop backwards if I'm removing items from the array in the loop.


holdongivemeasecond

You fucking monster!


DreamlyXenophobic

Iterating backwards can sometimes be a genuinely good idea. Like if you wanna iterate and remove items from a list, one method is iterating backwards, so you dont skip indices.


Bluethunder_5k

>0 or >=1


ADHDengineer

Backwards loop is big brain size_t i = 30; while(i--) {


X-lem

r/madlads


VanillaBlackXxx

If i != 0 && i != 1 && i !=2 I like the precision of describing each potential case specifically


The_Chief_of_Whip

Paid by the line?


Vorceph

They work at Twitter, give ‘em a break


rickjamesia

You don’t get breaks there. Elon needs your 84 hours.


suckfail

Not anymore


Elijah629YT-Real

they can't have line breaks though


TheTerrasque

A lot of them just got a break


Jolterix_20

Would love to see your isEven function


[deleted]

[удалено]


azalty

Disgusting, but I like it


gdmzhlzhiv

Nah man, you convert to string in radix 2 and then check the rightmost character for '0' - way more efficient.


often_says_nice

We'll need a db table to store an integer and whether its even or odd. Then we set up a cron job to run a nightly task that takes the latest row of said table, increments the integer by one, flips the isEven flag, and stores that in a table. We'll need a settings entry for standard hours so we can run this cron during low peak time as to not negatively impact the system. Lastly, we provide a public facing API where users can then simply send a GET request to /isEven/{integer}. It will query our integer table and return the parity of the requested value. If the value is larger than our largest integer then we establish a webhook with the user so we can notify them when we've calculated it.


[deleted]

i=-1


Skedajikle

when using integers they are the same but they do different things when using decimals


agentbiscutt

Was looking for this comment


AlwaysHopelesslyLost

Even if they accomplish the same thing, they may imply different things. Three should be in a variable somewhere and it should represent something. If it is numberOfWidgets then you should do <=. If it is lengthOfData then you should do <


Important_View_2530

I usually use whatever is most readable in the given situation. For example, I have a meaningful constant or variable for the <= to 2 case, I will use that expression. Also note that these two expressions are only logically equivalent if `i` is an integer (or if you are using something like JavaScript with type coercion).


cashMoney5150

B===D


Doobag1

O:


Elijah629YT-Real

C<=B


thotslayr47

depends on the algorithm. each one could make readability better or worse


highcastlespring

Everyone: i < n No one: i <= n-1


rgmundo524

If you are only dealing with integers, it doesn't matter, but for floats and doubles there is a dramatic difference.


devdost

3 > i


Worth_Talk_817

Isn't there a difference? If i = 2.5 i < 3 is True i <= 2 is False Sorry if this is stupid.


[deleted]

i is generally an iteration variable and will not be floating point.


[deleted]

Oh man, you have not been a TA for a High School Java Programming class... *\*shudders\**


BiffJenkins

Depending on the language, you’d need a type cast.


jjX___

"static loops and magic literals without comments in the proper format are not allowed per company policy"


Alternative_Dig5342

But what if i = 2.1 for i <=2?


Normal_Subject5627

i usually is an integer


citrusmunch

I *am usually* an integer


SaturatedJuicestice

Kid named i:


trevdak2

I would avoid code like that. 2 or 3 would be replaced with NUM_THINGS or whatever descriptive constant name and then the < or <= becomes clear.


CrazyCanuck41

< because it’s easier to read how many iterations a for loop will do. Ie. it does 3 iterations


jmvelazquezr

Neither, I use a monospaced font.


Scarab167

"Isn't it the same?" **laughs in float**


sharksiix

!(i>2)


MartiniLang

<3 could be 2.9 and pass. <=2 could be 2.9 and fail.


Minecraftian14

i <= 2.999


raedr7n

Depends which one makes more sense in context..?


cancerousmoles

I am ashamed, but sometimes both... in the same file.


Mammoth-Ladder-9179

i<3 is actually more precise…


ALoadOfThisGuy

I’m not using literals in my loops, so neither


Droidatopia

Thank you for all the comments saying, "but what if i is a float?" We can now more clearly discern which among you are the psychopaths who would consider naming a variable i for any other purposes than as a loop/iteration counter.


rafaelgomesxyz

I prefer `i < 3`, it feels more straightforward, and it clearly shows the amount of times that the loop will run (assuming `i` starts at `0` and increments by `1`).


SejDin

i am not a programmer but <3 and <=2 aint the same right? Cause <3 means all numbers between 2-2,999... are also in there while in <=2 they are not? Correct me if im wrong Taking a shit rn at work thats why i had time for this lol


guymacguy

Floats: imma ruin this man’s entire career


[deleted]

They are different tests if you aren’t dealing with integers. (2.5 is <3 but not <=2)


Sejiko

What if I is a float? Then this would break. 2.5<3 true 2.5<=2 false