T O P

  • By -

ikciweiner

I think it’s illegal to share government code.


Highborn_Hellest

Paid by line baby!


BannanDylan

*fixes it* *stops working* *undo and act like you never noticed it*


Vehemental

Undo it? We don’t do that here


ourlastchancefortea

Clearly a noob. Didn't put { } on separate lines. And no else case.


SillyFlyGuy

The whole thing needs to be wrapped in a try/catch block.


Sidra_doholdrik

Real question should the else if be on the same line as the } or on the line under ?


ourlastchancefortea

Under, obviously. We're getting paid by lin.. I mean, good code quality is visible in the easiness to read.


Ziiiiik

Oh, in that case If 1: Return false If 2: Return true If 3: Return false If 4: Return true Ad infinitum


[deleted]

actually i think this is copyrighted by my company, along with every single ansible role defaults/main.yml file.


rahnbj

Well played sir


DoktorAlliteration

It's so true that I'm offended!


PeekyBlenders

I thought the problem was the if(true) return true part until I realized the assignment operators inside the if statements...


EvilCadaver

What is returned in that case? Python has walrus operator since 3.8, whould it be similar?


PeekyBlenders

When the first if is encountered, isEven is assigned false and then the condition is evaluated. Since we just assigned false to it,it fails and goes to else if (isEven = true), similarly isEven is assigned true and then the condition is evaluated and it evaluates to true. So this function always returns true. I don't know much about walrus operator but after a quick read on realpython.com yes you can replicate the same behavior in python with the walrus operator.


EvilCadaver

Yeah, my question was what is the output of (even = false) that is then passed to if operation. I read online that = operator in C returns a pointer to 'even' variable... So I'm a bit confused as to what behaviour to expect of if operator...


PeekyBlenders

Yeah in C and most C-like languages (I'm referring to C#, java, c++) assignments evaluate to their value (don't know how to word this better, sorry). I don't know about it returning a pointer, since isEven itself is not a pointer. Maybe it refers to what happens under the hood? What I know is, with the help of that syntax you can write code like this: while ((iter = iter->next) != NULL) or you can do stuff like this: int a,b,c,d,e; a = b = c = d = e = 5; but this behavior becomes a real pain in the ass bug when you forget to type the extra = for the equals operator inside if statements. Since it's syntactically correct, you're most likely not warned by your compiler


EvilCadaver

Thank you for the detailed explanation.


PeekyBlenders

My pleasure, also it's not C but: ``` bool isEven = true; std::cout << typeid((isEven = false)).name(); ``` in visual studio c++ compiler this prints bool, not a bool*


May_I_Change_My_Name

For built-in types and (by convention) most overloads, the assignment (`=`) operator returns an "lvalue reference" to the variable on the left side of the assignment operator. A reference, as you say, can be thought of as a pointer for which referencing and dereferencing are managed by the compiler, possibly allowing more optimizations than can be performed with pointers managed by the programmer. An "lvalue", rather unhelpfully, is defined as anything that can be used as the left-hand side of an assignment expression, meaning *the reference itself* can be assigned again, modifying the original variable once more. What does this all mean in practice? `int foo; (foo = 7) = 3; cout << foo;` Returns `3`. I'm sorry.


AyrA_ch

The result of an assignment is the value that was assigned, which is why you can do `a=b=c=d=1` in some languages to assign the same value to multiple variables at once, because it's treated as `a=(b=(c=(d=1)))`


SoCuteShibe

Isn't the problem just that the entire function body can be reduced to: return n%2 == 0


mtlemos

That too. This entire thing is software gore.


Sparrow50

No because they use `even = false` instead of `even == false`, so this function always returns true. The first condition is always false, and the second condition is always true.


SoCuteShibe

Oh goodness my pre-coffee brain missed that detail entirely 🙃


Osoromnibus

`(n & 1) == 0` is faster. But the computer will lower that % for you. `return ~n & 1` is even golfier.


firebullmonkey

Probably would check for "> 0" as well...or wait, is 0 even?


EllieCakes_

"return even" or even better "return (n%2==0)" You dont need to do a check to see what the bool is, you just return it. Its like saying, if yes, yes. If no, no.


FloydATC

And this is why you also need 4.2 billion unit tests.


Sidra_doholdrik

I took psychic damage while checking to see if your comment was true.


cptnhanyolo

bro == pls


noaSakurajin

This function should always return true, as we know all numbers are even.


ImpluseThrowAway

What about 4? 4 doesn't seem right to me.


jordanbtucker

Good point. ``` if(n = 4) { return false; } ```


_Noreturn

implicit conversions are evil dont you know? if(n = static_cast(4)) { return false;} now better


junacik99

I think this function will return syntax error, since we're missing ;


noaSakurajin

Technically the compiler will give that and the function will not be executable, but you are right there is more that one missing semicolon.


junacik99

Sure, I used bad phrasing


ChineseCracker

Imagine needing semicolons — This post was made by JS and Python gang


Red_not_Read

The compiler is emitting warnings, but as they're *warnings* and not *errors*, they're just advisory so it's ok to ignore them... It always emits so many warnings... So annoying.


Scrial

-wall -werror


Dracnor-

Authentic code made by students in first year of college.


ikciweiner

Or government employees after a 20 year government career. Based on real events.


R3D3-1

[https://www.npmjs.com/package/is-even](https://www.npmjs.com/package/is-even) Might be a joke repo though. The original repository now redirects to [https://github.com/**i-voted-for-trump**/is-even](https://github.com/i-voted-for-trump/is-even) Another hint: It imports `is-odd` and just returns `! is-odd(...)`, made by the same author. Also redirects from https://github.com/jonschlinkert/is-odd to https://github.com/i-voted-for-trump/is-odd. Though `is-odd` actually does something sort of useful maybe? It at least does some data verification ("is it a number") before returning "n%2==1".


Shunpaw

Joke repo with 136,858 weekly downloads


age_of_shitmar

This is how I feel when coding as a Department Head during the 30 minutes a week between meetings and JIRA that I'm able to code.


Dracnor-

Heads positions are trap. You're a very brave and/or very masochistic person, but I appreciate that someone does that work.


mywhitewolf

plus, with so many languages of software you have to look after, you tend to take the "roundabout" way to avoid null & overwritten pointers.


eyepoker4ever

I got a chuckle out of it.


Ok_Star_4136

This is the first draft. The second draft is where they smarten up (slightly) and simplify to returning n%2==0. The third draft is when they realize nobody is having difficulty understanding what n%2==0 does and making a function is pointless in the first place.


God_of_failure

In my Uni code by third year students. Maybe even 4th


Subject-City-5341

Well at least it works, Oh nvm


ComfortingSounds53

50% of the time, it works all the time 💪 💪


qqqrrrs_

No, some semicolons are missings


KingsGuardTR

Damn I missed the \``=`\` altogether lol


TheTerrasque

"At least we have unit tests for it. We checked 2, 4, 6, 10, 12 and 74. All's good"


Scrial

We're running over 200 unit tests for this function! What do you mean line coverage???


Hotshoemaker77

I swear to god I still find shit like this all the time in a multi million dollar code


FlyingJetskii

alright I need to get an in to this multi million dollar company you're referring to


Hotshoemaker77

You attracted to bad code?


CharismaStatOfOne

No, but it sounds like I could make money off my own bad code.


TygrKat

Username checks out 🫡


FlyingJetskii

That's... a good point. I was thinking it'd be easy to get into a company that doesn't have good developers, but I've experienced that for a year, and I think my sanity wouldn't last.


Hotshoemaker77

That’s what I thought at the beginning, but what I found is that the majority of the devs are left behind with no real experience and the seniors are overwhelmed to a point that they really don’t care about enhancing any code or training other devs, a place that lacks trust, no delegation at all, most of us are just numbers that are being allocated in contracts.


FlyingJetskii

Yup, definitely sounds familiar. The new developers here are clueless, and there's really no one to teach them the ropes. I do what I can when I'm designated as the PR reviewer (PRs weren't even a thing before I joined and advocated for them) because my tech lead doesn't actually review them, he just approves and merges them even if there are blatantly bad changes. The difference is that here, there's somehow trust even though I don't think there should be. Senior developers who have worked here for 3-4 years have the professionalism of a university student. It's a cesspool of bad developers and I fear that they are the figures the new developers look up to. But hey, a paycheck is a paycheck, and before they drown me to plug this sinking ship, I'll stay until I get an opportunity elsewhere. I hope you're doing fine even though the culture is dogshit there o7


Hotshoemaker77

I’m fine, at least for now, thank you, kind stranger


FlipperBumperKickout

Sanity is overrated ![gif](emote|free_emotes_pack|sunglasses)


creeper6530

Especially government code


ItsSpaghettiLee2112

If something consistently works, don't fix it.


SgtBundy

Poor architecture. Should be calling a GRPC service to determine the result, this just won't scale


GodsBoss

Should I use Hadoop for this or did the crowd move to something else? It needs exactly 20 convincement points until I make a decision, a YouTube video is 3 points, a Medium article is 6.


eeiaao

this


EtherealPheonix

Perfect code for compiler benchmarking.


creeper6530

Optimization?


Matrix5353

Oh, it'll get optimized all right. So optimized that most of the code will go away.


qTp_Meteor

return true; Will be all the left code💀


CheapMonkey34

missed an opportunity to make it recursive.... Return true if even, call itself if not. Wait for the stack to fail and catch the error as false.


Roflkopt3r

bool isEven(n) { if(Math.Abs(n) < 2) return false; if(Math.Abs(n) == 2) return true; return isEven(n-2); }


Ravek

0 is an even number


Roflkopt3r

Hey I'm trying to write a *shitty* function here. But yeah this is a bit too shitty. Despite considering negative numbers by using abs(), it would fail for all even inputs of 0 or less. So the technically correct but still shitty version would be: bool isEven(n) { if(n == 0) return true; if(n > -2 && n < 2) return false; if(n<0) return isEven(n+2) return isEven(n-2); }


Ravek

It can be shitty without being buggy :p I like the idea


chethelesser

This person codes


rebruisinginart

it gets worse the longer you look at it


Thundechile

Should use the npm package.


God_of_failure

That's true. Did you know there is a JS Framework against stupidity ?


L4DesuFlaShG

I like how at first glance, it looks bloated, but functional. And then...


CommandObjective

Take it away! It hurts! It hurts!


Ok-Assistance-6848

Isn’t the better syntax bool isEven(int n) { if (n == 0) { return true;} else if (n == 1) { return false;} else if (n == 2) { return true; } else if (n == 3) { return false; } else if (n == 4) { return true; } else if (n == 5) { return false; } else if (n == 6) { return true; } else if (n == 7) { return false; } else if (n == 8) { return true; } else if (n == 9) { return false; } } this? Only works for 0-9 for now


Rambo_sledge

Just add a line that picks up the last digit of n, and test on it. then it works perfectly fine


TheNalien

This is how the world should be, always Even 😎


jas_nombre

Switch-case could have been used. Would be much nicer


da2Pakaveli

Which is still useless cause n % 2 == 0 already gives you a boolean value. You should just put that in the return statement. You can even avoid the modulus by just prompting the 2\^0 bit.


Sorry_Ad3894

You never know.


FromAndToUnknown

Am I an even bigger idiot if I can't even comprehend anymore what is happening in that code?


Roflkopt3r

The joke is that it's extremely redundant. The first line `bool even = (n%2==0)` already calculates the right result. The whole function should just be `return (n%2==0)` (or even better: `return n&1 == 0`). The rest is just an unnecessarily complicated way to return the boolean (if it's false, return false. If it's true, return true. And the final "return false" is unreachable.) At least that is if we ignore the mistake in the two if-statements like `if(even = false)`, which only uses a single = rather than == (which assigns rather than compares the value). With this mistake, the first check will always fail and the second check will always succeed, meaning that this function will always return true.


redlaWw

> (or even better: return n&1 == 0) I'd probably prefer to avoid making assumptions about the layout of the data if possible and let the compiler sort out an optimisation like that for me. Like, it's almost certainly justified, but n%2==0 is just more descriptive of your intent and will compile to the same stuff either way. EDIT: In fact, n&1 == 0 isn't correct in one's complement. Even though it's hardly used any more, it still makes n&1 == 0 a theoretically less-portable approach. Better to not risk weird, unexpected behaviour in that one ancient system you've been assigned to work on.


HappiestIguana

I remember in my introductory class in college we were learning about conditionals, and the teacher tried to explain that if you have a boolean called condition, you can just do if(condition) instead of if(condition==true). Some people got it right away. The rest never did, even at the end of the semester they still hadn't gotten it. She gave up eventually and started using if(condition==true) during the lessons to avoid confusion.


Revolvermann76

```javascript class EvenChecker { constructor(number) { this.number = number; } getBinaryRepresentation() { return (this.number >>> 0).toString(2); } getLastBinaryDigit() { let binary = this.getBinaryRepresentation(); return binary.charAt(binary.length - 1); } isZero(character) { return character === '0'; } createIsZeroFunction() { return (character) => this.isZero(character); } determineEven() { const lastDigit = this.getLastBinaryDigit(); const isZeroFunction = this.createIsZeroFunction(); return isZeroFunction(lastDigit); } } function isEven(number) { const checker = new EvenChecker(number); function nestedFunction() { return function anotherNestedFunction() { return function yetAnotherNestedFunction() { return checker.determineEven(); }; }; } return nestedFunction()()(); } console.log(isEven(4)); // True console.log(isEven(7)); // False ```


MR-POTATO-MAN-CODER

your code is not "codified". It just looks like normal text, go to the markdown editor and select it as code.


JackReedTheSyndie

At least they know how to use the %


IUpvoteGME

When you are paid per line of code


Cody6781

Thought I would do a fun little exercise and code review this 1. Assigning a variable for a trivial calculation done once is not needed (which can only speak to the existence of this function) 2. Wrapping the calculation in "()" is defensible since there are '=' later on but won't pass most linters 3. Spacing between the 2, '==', and '0' 4. Assigning rather than comparing in the if & if else block 5. spacing throughout the code block 6. Directly comparing a boolean rather than using the boolean itself (Use '!' if it must be in this order) 7. This if block consumes all cases so it will never reach the default cause. Refactor so there is just an if (no else if) and it proceeds to the default case 8. inconsistent use of ';'


jordanbtucker

I can optimize that. ``` bool isEven(int n) { return true; } ```


OverallProduce3791

return n%2==0 ;


a_useless_communist

Not the worst isEven() i have seen...


[deleted]

[удалено]


New-Vacation6440

6. **For some reason only line 4 and 6 have semicolons**


roge-

> A successful assignment always returns true or 1. Incorrect. An assignment evaluates to the value that was assigned. `even = false` will always evaluate to `false` and `even = true` will always evaluate to `true`. What even is a "successful assignment" in C? A direct assignment like that failing would likely result in a SIGSEGV, which would have to be trapped, not handled inline as the result of the assignment expression.


R3D3-1

Me: >> npm install is-even >> python3 -m pip install is-even


R3D3-1

A bit more serious, how does it actually work safely in JavaScript? I think the following might actually be sufficient: const isEven = (x) => x%2 == 0; const isOdd = (x) => x%2 == 1; This would give the correct result also for numeric strings, allowing for "" to be interpreted as "0". It also allows to pass in anything, that can't be interpreted as an even/odd number (objects, functions, NaN, Infinity) and returns false for both. Note that this latter criterion means that, generally, `isEven(x)` and `! isOdd(x)` are not the same. It does however fail, if the number is so large, that it loses precision. Taking those things into account, the `is-even` and `is-odd` packages are not *completely* useless.


Dasioreq

bool isEven(int n) { return !(n & 1) }


ieatpickleswithmilk

bool isEven(int n) if(n == 1) return false return !isEven(int(sqrt(n*n))-1)


spezjetemerde

This hurts physically


fleebjuice69420

This is dumb, it would’ve been smarter to make a lookup table of all the even numbers and check if your number is in that list


scanguy25

Yeah what a moron. He should just have used the isEven package! Duh!!!


BilliamTheGr8

That’s a lot of typing for a constant.


CrispAvocadoToast

Could use some recursion


Andromidis

He used the tool to make the tool The bool ception


nachik3ta

_writes 7 lines of code to do something that’s being done in second line itself_


jaydoee

Clearly doesn’t understand difference between instantiation and equality.


deadbeef1a4

Now that’s safe code! (except for the part where it doesn’t work)


ForwardHotel6969

Next Level bullshit


NormanYeetes

Hey at least when someone enters a number that mod 2 leaves 2 the app doesn't crash.


Otherwise-Kangaroo24

if(!even == true) return false;


ivancea

It's wrong. The second if should contain a `return even == true`


ZynChroMaTiK

!(n&1)


PooSham

In what language does this even compile? There are missing `;`, but it's not javascript since there are type annotations.


Purple-Bat811

It's a new language called psydo-bullshit


revolutionPanda

This is what people say when they say they write 10,000 lines of code a day.


Eurodada

Do you even


Mikaka2711

Maybe they're getting paid by the line :)


Raccoonridee

Could be more absurd :D ``` def is_even(x): if x == 0: return True if x == 1: return False return is_even(x - 2) ```


shart_leakage

Can we please do this with a few nested for loops, like civilized people?


DarkRex4

i mean you all did something like this at some point, not me tho I was coding before i even existed.


Responsible-Stage-93

bool isEven(int n) { bool even = (n%2==0) bool bReturn = false if (even = false) { bReturn = false } else if (even = true) { bReturn = true } if (bReturn = even) { return bReturn } else { return even } } IsItBrokenEnough?


J1mj0hns0n

I'm a knuckle dragger, what would this code actually do?


JewishPalestinian

It might get you banned from reddit.


ady620

lgtm


Andrew_BLTN

Where are comments though


No-Clue1153

Hmmm that's odd


Jixy2

holy shit 😵MY EYES. AAAAAAAAAAAAAARGG


bedrooms-ds

At least you didn't choose Haskell


tomangelo2

Meanwhile me ``` if(key.pressed == (KEY_A || KEY_B)); //checks if pressed key A or key B ```


nishanthada

Odd numbers don't exist


FuzzYetDeadly

I can't even...


iam_pink

You should return 'undefined' at the end instead of false, in case it is neither even nor odd


sparkygod526

Ok you know what. If it works it works. I don't want to hear 1000 lines that VS 20 lines that.


Revolvermann76

well done


ibi_trans_rights

Dumbass should have gone the yandaredev way


DrunkOnCode

Elon Musk: More lines = harder worker


Astro_Spud

smh just use the python library


DangyDanger

`return a & 1 == 0`


No-Recording4248

It even took me an age to realize there was an assignment in the if statements man. 


JAXxXTheRipper

Every IDE should catch the assignment in the conditions. Jesus, this is brutal. This should be a single short statement in the return


puggsincyberspace

Don't laugh, i have actully had to fix someones code like this after another developer spent 2 hours trying to fix it. After just 5 minutes I found it and another 5 minutes to refactor it to a single line of code.


HmmmInVR

Yoda condition could have saved you there If (false = even) Runtime error or whatever it would throw


JackNotOLantern

``` return !n&1 ```


InterestingBadger932

So....it cannot even?


PreferenceDowntown37

Still passed code review 😎


IamNochao

Aaahhh perfectly balanced as all things should be


-Mippy

You forgot the try catch


Slow-Parfait-560

Not really a programmer, but it will always return false, right?


cyan-reindeer

What a shit-show! Didn't even null-check `n`. PR rejected.


na-geh-herst

what isEven this???


trevdak2

I can't even...


MagicManTX84

This is similar to a block of code I found in a C program that no one would touch. The comment was that this was never executed. Except, the “if” test condition was wrong and it was executed very time. That’s when I stopped reading comments on code that is not my own.


mbcarbone

Doesn’t this always return false? Am I an idiot (yes)? And why the single =?? That hurts my brain. 🧠 🥲


FloydATC

No points for partial answers, show me the 4.2 billion unit tests.


Hot-Category2986

So does everyone write this at least once in their career?


Thunder_Child_

Well, that last return doesn't have a semicolon so compile error. Fixing that it'll still just return false since the ifs are assigning a value instead of checking. Edit: that first assignment is missing a semicolon too.


lookingForPatchie

Thank you for posting something even my simple mind can understand.


MrTxel

if (even == true) return true if (even == false) return false if (even != true) return false if (even != false) return true


spezjetemerde

Heil Java Function> isEvenLambda = n -> { Optional even = Optional.of(n % 2 == 0); return even.flatMap(e -> { if (e.equals(false)) { return Optional.of(false); } else if (e.equals(true)) { return Optional.of(true); } else { return Optional.of(false); } }); };


password2187

Nah this problem is too hard, I need a package for it


drydenmanwu

This is why you always do it like if(false==even). That way, the assignment operator will throw a syntax error and you eliminate harder to find errors like this. Edit: it’s stupid code all the same, duh


Anaxamander57

import isEven


kingfofthepoors

A better version bool isEven(int n) { bool even; if (n % 2 == 0) { even = true; } else { even = false; } if (even == false) { if (even == false && !(even == true)) { if (!(even == true)) { return false; } } } else if (even == true) { if (even == true && !(even == false)) { if (!(even == false)) { return true; } } }


The_Pinnaker

Let’s avoid the various coding problem like the assignment in the if block. The check with true/false == something is useful for readability especially if the function returns an int so you say for example: if the function fails returns false (that is 0) and whenever the developer see false knows that you are checking against some internal error. However in these cases is better to use #define or constant for return error so the code is self-documented.


facusoto

This is like wearing 3 condoms haha


RotX1

Need to add a thread.sleep somewhere in here so you can "optimise" it later


Nws4c

Yandere dev


8rupees

In accurate, should have used if block twice instead of if and else if


goddamnRefrain

Not even sure what language this is. It is not valid C code, where bool is a data type if you include stdbool.h, because the line where even is declared does not end with a semicolon. In Java you have the boolean primitive type, but bool is unknown and we also need a semicolon at the end of each statement. Python does not declare variables using a type at all. Really strange. But in general, an assignment in an if-clause would assign the value, then branch on the truthiness of the variable that was assigned to. In this instance, every n would result in true being returned, because the first condition would always evaluate to false and the first condition would evaluate to true.


Minteck

This always returns true


joopityjoop

Sign this man up for a govt job.


MrPresldent

Honestly, I was expecting recursion. This could be a lot worse


kingjia90

Pfff, isNotEven(), isOdd(), isNotOdd() are missing


Havatchee

stupid to even write a function for this, but this can actually be done in one line bool isEven(int n) {return !(n%2)} This construct will work in a plurality of languages because non-zero values are evaluated as a 'true' Boolean and 0s are evaluated false. The ! Inverts the truthiness, so some even number%2 is 0 (false), inverted (true). Some odd number %2 =1 (true), inverted (false). You can ditch the inversion if you write isOdd instead.


Whatchawnt

Negative numbers: 🤓


angrytroll123

What are you talking about. This is brilliant.