r/shittyprogramming • • May 25 '15

if(true) { } else { }

http://imgur.com/1zQ0KXW
310 Upvotes

122 comments sorted by

45

u/Arco123 May 25 '15

There are multiple things wrong with this code

28

u/[deleted] May 25 '15 edited Feb 15 '25

[deleted]

16

u/Arco123 May 25 '15

Usage of 'yolo' for starters :'(

4

u/SixFootJockey May 26 '15

I'm assuming it doesn't translate to anything in Dutch?

6

u/Illusi May 26 '15

No, but usage of the acronym has penetrated our young generations too.

1

u/Arco123 May 26 '15

Unfortunately so.

37

u/cdrt May 26 '15

0

u/[deleted] May 26 '15

[deleted]

1

u/senntenial May 26 '15

oh god is this bad to do

4

u/[deleted] May 26 '15

What? Pushing to master?

1

u/phail3d May 27 '15

Force pushing.

1

u/[deleted] May 27 '15

Nah force pushing is okay in the right context. I use it a lot when I have to rebase a co-worker's changes into my branch after it's been published.

1

u/Illusi May 26 '15

As variable name for short-lived variables that are only allocated once?

47

u/[deleted] May 25 '15

Seems to me the writer hadn't worked out the conditional yet, and went about writing enclosed code first, then forgot to go back and change it.

I've done it before, minus the forgetting part. I work in Java, so I toss a TODO there so I don't forget it.

8

u/Arco123 May 26 '15

Yes, but this 'validation technique' has been used throughout multiple classes and has been pushed to main.. Meaning it was 'ready' for deployment ;_;.

9

u/baggyzed May 26 '15

// TODO: Remember to get milk.

18

u/Binzi May 26 '15

Got 12, they had eggs.

3

u/indigo945 Jun 01 '15

IMO it should really be 13.

getMilk(1);
if (theyHaveEggs()) {
    getMilk(12);
}

1

u/the_noodle May 28 '15

I work in Java, so I toss a TODO there so I don't forget it.

I think I'm missing something here.. does java have some sort of extra support for TODO comments? I just rely on syntax highlighting and grep no matter what language I'm using.

1

u/huopak May 26 '15

In my experience it's way more common that people are just too lazy to properly remove a not needed condition and outdent the code.

10

u/Raannndy May 26 '15

while(true) isn't necessarily a bad thing to do. One of the arguments against using a do{ } while() loop is that you have to scroll down / lose reading context to see the breaking condition. If you want to avoid doing that and still only break on certain conditions, a while(true) is the best way because someone else reading your code will know exactly what they're about to get into.

There are obviously counter examples here, but I don't think while(true) is always a bad thing.

7

u/poop-trap May 26 '15 edited May 26 '15

I totally agree, but maybe that's because I'm a Python programmer and other than your use case there's also the generator pattern:

def is_prime(n):
    # your magic interview question code here

def gen_prime(x):
    """ Simple prime number generator """

    while True:
        if is_prime(x):
            yield x
        x += 1

primes = gen_prime(10)
print primes.next()
# 11
print primes.next()
# 13
print primes.next()
# 17

2

u/plexxonic May 26 '15

Yeah, Uhmmm, What the OP posted, That's not a loop...

while(true) is fine in some cases.

A long time ago a company I worked for had a guideline for doing it. while(1=1) essentially to highlight those.

1

u/[deleted] May 26 '15 edited May 26 '15

I use while(true) all the time and only recently found out that it's considered bad practice. I don't know what the fuzz is all about, you can accidentally create an infinite loop with while(var <= 10) or something similar as well. As long as you make sure that the loop is not overly complicated and properly quits at the right time, the basic logic is really not that different from constantly checking the value of a variable.

3

u/[deleted] May 26 '15

It's bad practice because you're not trying to make an infinite loop in 99.99% of the cases. It's always something like:

while(true) {
    . . . 
    
    if(!condition)
        break;
}

In that case, just do:

do {
    . . .
} while (condition);

It's both more readable and shows proper semantics (loop until some condition isn't true).

2

u/[deleted] May 26 '15 edited May 26 '15

Lots of language don't have this. In the languages I use most, while true's make perfect sense.

In Python :

while True:
    do stuff
    if condition:
        break

In OCaml :

try while true do
     do stuff;
     if condition then raise Exit
done with Exit -> whatever

1

u/almightySapling May 26 '15

I don't get some "bad practices".

Is the code I wrote legible, effective, and easy for both human and compiler to understand? Then that's good code, EOL

3

u/[deleted] May 26 '15

It's opgeslagen.

1

u/Arco123 May 26 '15

Very much!

43

u/GamerNebulae May 25 '15

Realising a Dutch person wrote this makes me sad...

16

u/Arco123 May 25 '15

Why does that make you sad? :O

50

u/tgb_nl May 25 '15

I expected more from my people

6

u/Arco123 May 26 '15

It's okay, though. We're from Belgium. I just clean up messes wherever needed.

1

u/Nkast May 26 '15

Is it common for people to deliver 'ready for deployment' code like that and are they as you would say, professionals?

3

u/Arco123 May 26 '15

No, we're actually students working on a large scale project. Groups are formed randomly. There are two stronger members, three weaker.

They figured it was fine and merged it in main.

1

u/Nkast May 26 '15

Ah I know what you mean. I have experienced this a few times as well. Good luck!

25

u/cyberbemon May 25 '15

That's a very high expectation mate, idiots exist everywhere :D

-4

u/kuilin May 26 '15

That's... racist?

13

u/deallocator May 25 '15

it's worse if you realize this is not the worst thing they did (I work on this project as well)

3

u/MaximaxII May 26 '15

Story time?

4

u/deallocator May 26 '15

can't really show you the "code" they wrote as we obviously reworked most of it asap but time logs like these aren't unusual http://imgur.com/pnaEEoC and of course there's this little gem http://imgur.com/M6gBxjk

1

u/Arco123 May 26 '15

Things like logging 5 hours for creating a basic GUI.

12

u/DonVittorio May 25 '15

// yolo geen cross platform meer da is super oh zo niet nuttig enzo oke, zwijg cout

Roughly translated: YOLO no cross platform anymore that's oh so not useful and all okay, shut up cout

Reading that hurt my brain.

1

u/deallocator May 26 '15

that's what you get if you take devops in the team

1

u/Arco123 May 26 '15

Devop for life.

30

u/SlightlyCyborg May 25 '15

This is how I comment out blocks of python code temporarily

6

u/80386 May 25 '15

This is one of my big Python frustrations: no block comments. The other one is readability.

26

u/Tynach May 26 '15

""" opens a block comment.

This closes it again: """

I think it technically starts a multi-line string, but you can have it anywhere in the code, which basically turns it into a comment.

6

u/RetardedChimpanzee May 26 '15

Technically it's a doc sting, not a comment. But it works quite well as comment. Plus you can call help() and see what all has been commented.

4

u/[deleted] May 26 '15

you can call help() and see what all has been commented.

oh fuck, mind blown

3

u/Sohcahtoa82 May 26 '15

Not quite correct.

A doc string is only a comment at the top of a function before code. You can put that in single quotes, double quotes, triple-single quotes, or triple-double quotes and it doesn't matter.

def myFunction():
    'This is only in single quotes, but it is still a doc string and will show up in help()'
    x = 5
    """This is in triple-double quotes and is just a normal comment and won't show up in help"""
    '''This is triple-single quotes and is no different.'''

A doc string is only defined by the fact that it comes immediately after the function def. Putting them in triple-double quotes is only a convention.

1

u/Navith May 26 '15 edited May 27 '15

It also helps that strings that aren't assigned to variables and aren't at the beginning of a function/class don't produce any code.

0

u/[deleted] May 26 '15

[deleted]

1

u/ertlun May 26 '15

If the multi-line string within the comment uses single quotes, use double quotes for the "comment," and vice versa. As long as you use the same quoting style consistently it won't be a problem.

5

u/MrPopinjay May 25 '15

You really need a better editor.

1

u/80386 May 26 '15

I'm using PyCharm. Is that bad?

1

u/MrPopinjay May 26 '15

I imagine PyCharm supports basic features such as commenting out blocks. In which case, I recommend you spend some time learning how to use your editor :)

1

u/Sohcahtoa82 May 26 '15

PyCharm is great. It DOES do block comments.

Select a block of code, press CTRL and slash (/). It comments out the block. Selected a block of comments and hit CTRL-/ again and it uncomments it.

0

u/[deleted] May 25 '15

[deleted]

9

u/discofreak May 26 '15

Its too readable. No challenge.

6

u/threeys May 26 '15

Yeah I really don't know what people are comparing it to if they think python's readability is bad

5

u/80386 May 26 '15

When I write a class, and come back to it later, a lot of the time I have no idea what the fuck I wrote or what it does.

It's not that individual lines are too complex to comprehend, it's just that the overall structure of classes and inheritance is a clusterfuck. For example, class properties are declared in the constructor. I know that's what happens under the hood anyway, but I mean, really? To write an abstract class, I need to declare "__metaclass__ = abc.ABCMeta" and annotate with "@abc.abstractmethod". What's wrong with an "abstract" keyword? "self" is an argument in every class method. Why? I still don't know what's up with the various variations of calling a superclass constructor.

Maybe I'm just be bad at python.

5

u/[deleted] May 26 '15

"self" is an argument in every class method. Why?

Nope, it's an argument in every instance method.

When you call a method of a class instance, it gets passed the instance itself as its first argument, without you having to specify it - because it would get super annoying always having to do foo.bar(foo).

A method without self as an argument, at least in Py3, can be called as a class method:

class Foo():
    def bar():
        print("42")

Foo.bar() # 42

2

u/80386 May 26 '15

instance method

True, that's what I meant.

When you call a method of a class instance, it gets passed the instance itself as its first argument

Of course, that's how it works under the hood in most OO-languages. However, isn't it the job of a programming language to hide these implementation details from the developer?

Python has a 'class' block. It would be sufficient to have instance methods inside the class block, and class methods outside the class block, like most languages do it. No need to have a separate 'self' argument that serves no purpose whatsoever except screen clutter.

1

u/[deleted] May 26 '15

It would be sufficient to have instance methods inside the class block, and class methods outside the class block

Wait, what?

class Foo():
    def instance_method():
        ...

def class_method():
    ...

Is that what you mean? Because class_method in this case is actually a global function, not related to Foo at all.

1

u/80386 May 26 '15

Not from where I'm standing...

When I write this:

class Foo():
    def class_method():
        ...

My editor complains: "Method must have a first parameter, usually called 'self'".

However when I declare it like this:

def class_method()
class Foo():

I can now call it from outside the class:

Foo.class_method()

Like I said, I might just be bad at python, but to me this seems to make sense.

2

u/[deleted] May 26 '15

My editor complains: "Method must have a first parameter, usually called 'self'".

Fuck, sorry! What I meant to write:

class Foo():
    def instance_method(self):
        ...

def class_method():
    ...

when I declare it like this

If your method declaration is not inside the class block, it has zero relation to that class.

0

u/[deleted] May 26 '15

[deleted]

1

u/80386 May 26 '15

That is not true at all in this case. The job of a language is to free your mind of the trivial, obvious stuff so you can focus on the stuff that matters. Or we could all go back to writing assembly...

0

u/[deleted] May 26 '15

[deleted]

1

u/80386 May 26 '15

...what? I didn't mention anything you just said. Just remove the self argument, make it implicit. It's not that hard. Way to put up a strawman.

3

u/arbuzer May 26 '15

you came from java/c# didn't you? trying to emulate one langugage with another is a bad idea, python has a little different class/object idea and should be used in slightly different way

2

u/80386 May 26 '15

Python is an object-oriented language. Is it unreasonable to expect to be able to express object-oriented concepts easily and efficiently?

1

u/arbuzer May 26 '15

python is more multiparadigm than OO in my opinion

1

u/Sohcahtoa82 May 26 '15

In Python, due to duck typing, abstract classes aren't even necessary. You can do this:

class Dog(object):
    def walk(self):
        print 'Dog walking'
    def bark(self):
        print 'BARK!'

class Cat(object):
    def walk(self):
        print 'Cat walking'
    def meow(self):
        print 'meow!'

animals = [Cat(), Dog()]
for animal in animals:
    animal.walk()

Dog and Cat here essentially have the same interface, but they don't inherit from a base Animal class like you might expect in another language. Of course, your IDE might have a hard time coming up with auto-complete suggestions, but something like this wouldn't work in Java/C++/(And I think C#) without creating a base class.

Really, in Python, declaring a class as abstract with all those decorators and metaclasses and shit is completely optional. You don't have to use them to have an abstract class. If you want to make sure that child classes implement specific methods, you can just make the parent class have a stub with a raise NotImplementedError:

class Animal(object):
    def walk():
        raise NotImplementedError

And now, you could make Dog and Cat inherit from Animal, and if walk() gets called on another Animal class that didn't define a walk() function, a NotImplementedError gets raised.

1

u/80386 May 26 '15

What if I want a bunch of shared functionality, but want to extend only 1 method?

2

u/Sohcahtoa82 May 26 '15

You mean like this?

class Animal(object):
    def walk(self):
        print 'Animal is walking'

    def speak(self):
        raise NotImplementedError

class Dog(Animal):
    def speak(self):
        print 'WOOF!'

class Cat(Animal):
    def speak(self):
        print 'Meow!'

class Squirrel(Animal):
    pass

animals = [Cat(), Dog(), Squirrel()]
for animal in animals:
    animal.walk()
    animal.speak()

Which would output:

Animal is walking
Meow!
Animal is walking
WOOF!
Animal is walking
Traceback (most recent call last):
    File "animals.py", line x, in speak:
        raise NotImplementedError
NotImplementedError

1

u/80386 May 26 '15

TIL, thanks

18

u/infected_scab May 25 '15

I have used if(false) as a way of disabling code as an alternative to commenting out, because it still gets checked for errors at build time.

10

u/barsonme May 26 '15

I like if (true === false) or similar.

Accidentally left that in without a comment once, and confused the hell outta our poor new developer.

2

u/Xelerons May 26 '15

What does three ='s mean as an operator? I've only ever seen two and google is shit for searching for stuff like that

4

u/jewdai May 26 '15

it's javascript. Since its duck typing it means it has to match value and type. example:

(5 == "5") <-- returns true.

"5" isnt null or undefined therefore returns true

 (5 === "5") <-- returns false. 

it returns false because it doesnt match the type or value.

2

u/Xelerons May 26 '15

so 5 === 5 would be true?

2

u/Ununoctium118 May 26 '15

Yep

1

u/[deleted] Jun 06 '15

What about 5===2

1

u/battery_go May 26 '15

If you want a more in-depth answer than what /u/jewdai wrote, take a look at this article (scroll down a little bit).

1

u/imranilzar May 26 '15

Yeah, I find this a normal way to temporary force an execution of an if-then-else block during testing. The shitty part is that it was obviously left over in production after testing, but it happens.

5

u/deallocator May 25 '15

I swear to god one of them just merged the main branch into his own branch and he literally had to deal with problems of 50 versions ago and he added like 36 files somehow http://imgur.com/c83M3h3

4

u/[deleted] May 26 '15

Oh god, those Dunglish identifiers.

1

u/deallocator May 26 '15

another gem for you guys http://imgur.com/GO0yZ89

1

u/Arco123 May 26 '15

That bit looks fine to me.

1

u/[deleted] May 26 '15

The fact that it's written in some sort of Dutch makes it bad already.

1

u/deallocator May 26 '15

I love the const memory allocation of the chars and the complete lack of finesse in this piece of code

0

u/[deleted] May 26 '15

[deleted]

1

u/Arco123 May 26 '15

Those aren't included in the picture, but they're there :D

1

u/GMKO May 26 '15

i think some IDEs will tell you that the else block is dead code

1

u/Arco123 May 26 '15

i think some IDEs will tell you that the else block is dead code

Visual Studio doesn't, but I think IntelliJ does this, yes.

1

u/beermatt May 26 '15

if (true == true) {}

1

u/Arco123 May 26 '15

if(true == true == 1) {}

3

u/[deleted] May 26 '15

I only speak German, my Dutch is very poor, but trying to read "yolo geen cross platform meer da is super oh zo niet nuttig enzo oke, zwijg cout" hurts my brain. I'm reading that as "yolo kein cross-platform mehr da ist super oh so nicht nuetzlich und so okay, still cout".

So, like... "Yolo, no more cross-platform, that is super, oh so unhelpful and so okay, silent cout." Er...what? And that's after me really trying to force it to make sense...

1

u/[deleted] May 26 '15

It doesn't make sense for me, a dutch guy, either.

3

u/KLDzzz May 26 '15

//nonsensical

lol

2

u/SupaHam May 26 '15

To be fair this isnt necessarily always bad. For example, when writing a patch and you want to eliminate the if statement in the least amount of lines, you'd set the test to true for the least amount of line changes.

1

u/trekologer May 26 '15

Very true and I do this all the time. I don't commit it to the scm though...

1

u/ILikeLenexa May 26 '15

If the billing system doesn't accept transaction creation commands from anything but the production server, and it's broken anyway, I can see committing it.

2

u/mrsqueakyvoice97 May 26 '15

no. no thats not right. stop that right now.

2

u/supergnawer May 26 '15

Awesome construction when you're paid by volume of code. Which really happens.

1

u/[deleted] May 25 '15

Zoetermeer?

1

u/shthed May 26 '15

I've seen this done in badly generated dynamic SQL statements full of things like WHERE 'Y' = 'N' OR 1 = 1 OR ( more conditional clauses )

1

u/sonicthehedgedog Jun 11 '15

This is a joke. It's clear the author should have used if else (false) {}. The code has to speak for itself, damn it.

-5

u/snarkyturtle May 25 '15

This is why people hate PHP.

7

u/devoidfury May 25 '15

Looks like c++ from here.

1

u/[deleted] May 26 '15

People also hate C++.

-1

u/snarkyturtle May 25 '15

You're right, didn't see the function declaration.

0

u/[deleted] May 25 '15

[deleted]

2

u/deallocator May 26 '15

it's not bad if used intentionally, it's bad if they think this is production ready code

0

u/[deleted] May 25 '15

[deleted]

2

u/badmonkey0001 May 26 '15

I'm just gonna pretend those are metal lyrics...

Cannot create voucher without any data!

1

u/poop-trap May 26 '15

I'm assuming this calls Cthulu to arise from the deep? Only acceptable use of an unexecutable block of code.

1

u/[deleted] May 25 '15

[removed] — view removed comment

2

u/invertedcheese85 May 26 '15

|| together all of the null checks, since the message is the same in each case

2

u/treycook May 26 '15

Speaking as a dumb PHP guy here, rather than have a multiple hundred line if block, I prefer to wrap everything in a try-catch block, toss in if's when needed and throw an exception. This allows me to handle multiple exceptions, with more specific error messages, without layering in more spaghetti if { if { if { } } }'s, which can get ugly and hard to follow. Additionally, it can keep your 'ifs' and 'elses' more grouped up, so you don't end up with an else out of nowhere, and having to scroll back up to figure out what the hell it's referencing.

E.g.:

if ($foo == 123) {
    ...
}
else {
    ...
}

Becomes:

try {
    if (!$foo) { throw new Exception ('No foo!'); }
    if ($foo != 123) { throw new Exception ('Incorrect foo!'); }
    ...
}
catch (Exception $e) {
    echo $e->getMessage(); // This prints the exception
}

Of course, it all comes down to knowing when you need a simple if-else block, and when you need to think ahead and handle errors properly. Think of if-else as a simple I/O light switch, sometimes that's all you need.

1

u/mobrockers May 26 '15

Wrap it in their own method because your if-else is most likely doing more than one thing. Which it shouldn't be doing.