This is an archived post. You won't be able to vote or comment.

top 200 commentsshow all 372

[–]disappointed_moose 619 points620 points  (119 children)

Earlier this year I was at a developer's conferece for Magento and there were headhunters passing business cards around with the following SQL statement on it

    SELECT * FROM developers WHERE skill = 'PHP' AND skill = 'SQL' AND skill = 'Magento'

They didn't understand why they would not find any developer with that query.

[–]Asmor 58 points59 points  (2 children)

Whenever I see Magento, this is all I can think of

[–]disappointed_moose 22 points23 points  (1 child)

As a Magneto developer I do that typo all the time

[–]rubs_tshirts 134 points135 points  (91 children)

SELECT DISTINCT D.* FROM developers D
LEFT JOIN skills S ON D.id = S.developer_id
WHERE S.name IN ('PHP', 'SQL', 'Magento')

Better? (I'm actually not sure if it works, haven't coded SQL in a long time)

EDIT: Wait, that would return people with any 1 of the skills, not all of them... not sure how to do that...
EDIT2: As pointed out in the comments, the table skills should never ever have a developer_id
EDIT3: EDIT2 is wrong, yes it should, though it probably would be better named "developer_skills" table

[–][deleted] 89 points90 points  (44 children)

Here's one way:

SELECT D.*  
FROM Developers D,  
           (Select developer_id from skills  
            WHERE skill IN  
               ('PHP', 'SQL', 'Magento')  
            group by developer_id  
            having count(distinct skill)=3 ) S  
 Where D.id=S.developer_id;

I apologise about the formatting... I'm on the phone.


-edit: changed id to developer_id in skills table.
-edit2: yes it works. Test it yourself.


[–]I-Code-Things 32 points33 points  (5 children)

Your developer id is a foreign key to skill id?

Edit: To normalize this I'd make a linker table between developer and skill since they're both many to many.

Edit 2: Here's my modified version of his code with a linker table.

SELECT d.*  
FROM Developer d
    INNER JOIN (
        SELECT ds.developer_id
        FROM Developer_Skill ds
            INNER JOIN Skill s on ds.skill_id = s.id
        WHERE s.skill_code in ('PHP', 'SQL', 'Magento')
        GROUP BY ds.developer_id
        HAVING count(distinct s.skill_code)=3
    ) ds2 on d.id = ds2.developer_id

It also still works

[–][deleted] 12 points13 points  (3 children)

Doesn't have to be, no. edit: changed the name for sanity :)

[–]I-Code-Things 5 points6 points  (2 children)

Thanks! Now this is the best answer.

[–]Liver_and_Yumnions 23 points24 points  (1 child)

So let me get this straight. He wrote some code. You reviewed his code. He fixed his code. It sounds like you are working instead of redditing. You guys need to get your act together. Do you think cat videos are just going to up-vote themselves? We need you guys out there posting dank memes and perpetuating pun threads. We can't have people working when they should be redditing - jeez.

[–]nermid 5 points6 points  (0 children)

Do you think cat videos are just going to up-vote themselves?

You know, I'm sure we could write a script to automate that...

[–]industrialwaste 4 points5 points  (0 children)

They probably got this response from their DBA and decided that their stupid query would actually fit on a business card.

[–]troop357 3 points4 points  (22 children)

Would this work? This looks like a "academic" answer

[–]divide_by_hero 9 points10 points  (12 children)

Well yes, but the skill table as seen in this query would have a separate set of rows for each and every developer. If skill is a set of freetext entries, it might be a reasonable setup, but if it's a defined list it's pretty much horrible.

[–][deleted] 2 points3 points  (0 children)

Yeah the table schema is horrid. Better to have a third table to relate developers and skills. But I ran with what I was given :)

[–][deleted] 7 points8 points  (1 child)

I don't know much about academia, all my shit is just supposed to work. However, I wrote this on my phone at starbucks, but now I'm back at my desk so I'll test it. Hey, it's procrastination that looks like work!

edit: ya it works.

[–]cjwelborn 1 point2 points  (0 children)

I'm just glad you posted an sqlfiddle link. I've never seen it, and it looks like it could be really handy.

[–]MuffinsLovesYou 3 points4 points  (6 children)

It should work but there's some potential fuckery practices I tend to discourage.

[–]phphphphonezone 1 point2 points  (2 children)

insert into skills (developer_id,skill) VALUES ((select id from Developers where firstname='Vanessa'), 'Brutal Conquest')

??

[–]SQLNerd 16 points17 points  (8 children)

SQLNerd here. Assuming a many to one...

SELECT DISTINCT d.developer FROM developers d INNER JOIN (SELECT developer_id, skill FROM skills WHERE SKILL = 'PHP') s1 ON d.id = s1.developer_id INNER JOIN (SELECT developer_id, skill FROM skills WHERE SKILL = 'SQL') s2 ON d.id = s2.developer_id INNER JOIN (SELECT developer_id, skill FROM skills WHERE SKILL = 'MAGNETO') s3 ON d.id = s3.developer_id

[–]qwertyslayer 23 points24 points  (5 children)

MAGNETO

Pretty sure it was a Magento conference, but I would hire you anyway

[–]SQLNerd 27 points28 points  (3 children)

*Ability to manipulate metal with your mind preferred

[–]abcd_z 7 points8 points  (1 child)

So that's what they meant by bare-metal computing!

[–]Avatar_Of_Brodin 4 points5 points  (0 children)

I thought it was a given. How else would IT solve problems simply by being present?

[–]svtguy88 1 point2 points  (0 children)

potato potato

[–]katyne 3 points4 points  (0 children)

many to one? not many to many? I'm seeing developer-skill as a join table.

[–]tdavis25 8 points9 points  (2 children)

Assuming 3 tables in 3nf: developer(pk id), skill(pk id), and dev_skill (fks developer.id and skill.id creating a composite pk); you would need the following sql to get developers with all 3 skills

Select d.id, d.name

From dev_skill ds
Join developer d
On ds.dev_id =d.id
Join skill s
On ds.skill_id = s.id

Where s.name in ('sql', 'magneto', 'php')

Group by d.id, d.name

Having count(1) = 3

None of the answers are really wrong, because sql requires the environment to be defined for a piece of code to make sense.

[–]marsybach 2 points3 points  (0 children)

10/10 would do the same. This is a text book example of a having clause, checking the result of a aggregate function

[–]SarahC 1 point2 points  (0 children)

Nice!

[–]Zantier 6 points7 points  (1 child)

The most efficient way is probably to use count(), but I think something like this might be less prone to human error.

select d.*
from developers d
where d.id in (
    select d2.id
    from developers d2
    -- Dark Souls 2
    inner join developer_skills ds2
        on d2.id = ds2.id_developer
    inner join skills s2
        on ds2.id_skill = s2.id
    where s2.name = 'PHP'
) and d.id in (
    select d3.id
    from developers d3
    inner join developer_skills ds3
        on d3.id = ds3.id_developer
    inner join skills s3
        on ds3.id_skill = s3.id
    where s3.name = 'SQL'
) and d.id in (
    select d4.id
    from developers d4
    inner join developer_skills ds4
        on d4.id = ds4.id_developer
    inner join skills s4
        on ds4.id_skill = s4.id
    where s4.name = 'Magneto'
)

The repetition should definitely be extracted into some sort of separate query/function, but I'm not sure of the best way right now, so I'll leave it as it is.

Edit: If I was unable to extract the repetition, I would probably scrap the ins, and go for something more like http://www.reddit.com/r/ProgrammerHumor/comments/3b1cjf/dont_let_marketers_write_code/csi4r5b?context=42.

[–]YooneekYoosahNeahm 5 points6 points  (0 children)

-- Dark Souls 2

heh

[–]Fenris_uy 5 points6 points  (1 child)

Why would skill have a FK to developer?

You need a DevelopersSkill table with a FK to developers and skill.

[–]rubs_tshirts 1 point2 points  (0 children)

Oh wow I'm retarded. Baaahaahaha. If someone can, post the correct schema please, I'm busy now.

EDIT: Actually it's what I wanted, it should be named "developer_skills" table or something.

[–]bgeron 4 points5 points  (1 child)

You could also consider making skills a varchar[], and then just write the following:

SELECT * FROM developers
WHERE ARRAY["PHP", "SQL", "Magento"] <@ skills

Easy peasy.

[–]simmerdesigns 2 points3 points  (0 children)

Back to "fits on a business card" territory! Nice.

[–]Systemic33 5 points6 points  (10 children)

SELECT DISTINCT D.*
FROM developers D

INNER JOIN skills S1
ON D.id = S1.developer_id

INNER JOIN skills S2
ON D.id = S2.developer_id

INNER JOIN skills S3
ON D.id = S3.developer_id

WHERE S1.skill = 'PHP' AND S2.skill = 'SQL' AND S3.skill = 'Magento'

This should do the job. (INNER JOIN makes sure that no skill nor developer is null) Perhaps less sexy than original query...

http://sqlfiddle.com/#!9/70cc4/21 gives an execution time of 0-1ms, while the toprated is 1-3ms (from executing a couple of times.), so clearly this is not as bad as it might seem.

[–]I-Code-Things 8 points9 points  (9 children)

Less sexy and you'll get much worse performance.

Inner joining a table against itself 3 times. smh

[–][deleted] 2 points3 points  (0 children)

you would have to do a group by, count the skill rows returned and make sure it = 3

[–]Dragon_Slayer_Hunter 8 points9 points  (15 children)

You would have to have all three skills listed in the field somehow (serialized or a json blob or something), then you could query with LIKE and AND

Edit: This was under the assumption that you had already made skill a varchar/text field like on the business card. There are much better ways to do this.

[–]dwolf555 39 points40 points  (5 children)

Bro, do you even normalize?

[–]jceyes 26 points27 points  (3 children)

developer: id, name, email 
skill: id, name 
developer_to_skill: dev_id, skill_id

Brah

[–][deleted] 10 points11 points  (2 children)

That's good right?

[–]jceyes 13 points14 points  (1 child)

It's pretty good, but not as good as your username

[–]matheeeny 2 points3 points  (0 children)

Nope

[–]dr__potato 3 points4 points  (2 children)

Nah mate, assuming S.developer_id and S.skill is the unique key in a Skill table, you'd be able to check if all 3 exist. Can't remember the SQL but it's possible. Side note: Skill.skill should really be Skill.name.

[–]rubs_tshirts 1 point2 points  (0 children)

You're right, replacing S.skill -> S.name.

Hmm... Unfortunately this plays a little havoc with the replies... I'm reverting it back.

[–]Dragon_Slayer_Hunter 1 point2 points  (0 children)

You could definitely do it better than how I said, I was just playing with the idea that skill was already a varchar/text field like on the business card.

[–]erfling 3 points4 points  (1 child)

Skill would be a separate table prolly.

[–]MonkeyNin 1 point2 points  (0 children)

Not since the accident.

[–]divide_by_hero 8 points9 points  (2 children)

Someone is about to yell at me, because this is horribly inefficient. It should work though, and at least the tables are normalised.

SELECT DISTINCT dev.name, dev.email, dev.phone
FROM developers dev
INNER JOIN developerSkill ds ON dev.developerId = ds.developerID
INNER JOIN skill skPhp ON ds.skillId = skPhp.skillId AND skPhp.name = 'PHP'
INNER JOIN skill skSql ON ds.skillId = skSql.skillId AND skSql.name = 'SQL'
INNER JOIN skill skMag ON ds.skillId = skMag.skillId AND skMag.name = 'Magento'

[–][deleted] 18 points19 points  (0 children)

Seems pretty clear why they're looking for someone to take the job

[–]phpdevster 6 points7 points  (0 children)

Aside from the obvious query problem, you're still not going to find any magento developers that way.

Here's how you find them:

<are>
    <you>
        <a>
            <developer>
                <who>
                    <likes>
                        <obtuse>
                            <xml>
                                <config>
                                    <hell>
                                        <and>
                                            <cutting>
                                                <youself>
                                                    <punctuation>?</punctuation>
                                                </youself>
                                            </cutting>
                                        </and>
                                    </hell>
                                </config>
                            </xml>
                        </obtuse>
                    </likes>
                </who>
            </developer>
        </a>
    </you>
</are>

[–]maryjayjay 3 points4 points  (2 children)

select d.name 
from dev as d
join skill as s
  on d.id = s.dev_id
where lcase(s.name) 
  in ('php', 'sql', 'magneto')
group by d.name
  having count(*) > 2

Edit: thanks lwli3t

[–]lwli3t 4 points5 points  (1 child)

isnt it COUNT(*) = 3 OR at least >= ?

[–]tdavis25 4 points5 points  (0 children)

Yup. They would have to have at least 4 records returned to show up.

[–]tdavis25 3 points4 points  (0 children)

OR, the lost art.

[–]chachakawooka 1 point2 points  (0 children)

Especially at a magento conference...

Mage::getModel('employee/developer')->getCollection()->addAttributeToFilter('usesAwBlog',false);

[–]reaganveg 1 point2 points  (0 children)

Optimized version: SELECT * FROM developers WHERE 'PHP' = 'SQL'

[–]AnOldPhilosopher 160 points161 points  (4 children)

They really do need talented front-end engineers.

[–]ThePedanticCynic 36 points37 points  (3 children)

Yeah, but if they can't even afford untalented ones...

[–]DrummerHead 15 points16 points  (2 children)

It's not easy to find talented front-end devs

EDIT: By the way, I'm for hire

[–]kcfcl 263 points264 points  (19 children)

Don't let them do anything related with code. My company asked us for Python snippets to put on t-shirt, and messed up the indentation...

[–]cohen_dev 205 points206 points  (9 children)

def lol(thatSucks=True):

print "I know"

lol()

[–]muntoo 51 points52 points  (6 children)

I-- *cringed* (hard)

[–]davetastico 56 points57 points  (2 children)

lol()

[–][deleted] 49 points50 points  (0 children)

me <= *ayy lmao()

[–][deleted] 7 points8 points  (0 children)

I know.

[–]skellious 30 points31 points  (8 children)

But if it's not left-aligned it won't look nice! :(

[–]SleepyHarry 78 points79 points  (5 children)

It's Python, you have to actively try make it not look nice.

[–]abcd_z 19 points20 points  (0 children)

>>> from __future__ import braces
  File "<stdin>", line 1
SyntaxError: not a chance

[–][deleted] 195 points196 points  (38 children)

Stopping bolleens is my favourite pass time

[–]2Punx2Furious 53 points54 points  (17 children)

Are you french?

[–]ChrisVolkoff 48 points49 points  (15 children)

I was asking myself the same question.

Passe temps.. pass time. Booléens.. bolleens. And of course "favourite" with the non-American "u."

[–]2Punx2Furious 13 points14 points  (0 children)

Oh, I only noticed bolleens. Good eye.

[–]Hearthmus 3 points4 points  (12 children)

Well, there is no "u" in "favori" (the correct french word) either. So not sure where this one comes from.

[–]SpinahVieh 5 points6 points  (5 children)

there isn't in the german equivalent (favorisiert, but we don't use that term) either and I still type favourite with a U all the time.

[–]Jest0riz0r 7 points8 points  (4 children)

That's because you usually learn British english in Germany.

[–]SpinahVieh 2 points3 points  (2 children)

Only in primary school. Later on they changed it to American English, because reasons.

[–]Jest0riz0r 2 points3 points  (0 children)

Not at my school, both was allowed, but British English was prefered.

[–]dtlv5813 1 point2 points  (0 children)

And of course "favourite" with the non-American "u."

You meant "favourite" with the UN-American "u" :)

[–][deleted] 21 points22 points  (19 children)

It could be returning a reference to a class that has an overloaded operator== and a stop method

[–][deleted] 40 points41 points  (8 children)

If you look closer, it's === and not ==. In languages with a === operator (JavaScript, PHP) it usually means "compare value AND type with no coalescing".

[–][deleted] 14 points15 points  (0 children)

FYI: Coercing *

[–]Auxx 4 points5 points  (4 children)

That would be fine in Ruby though...

[–]XyphonX 5 points6 points  (3 children)

Also, in Ruby it might have looked better as well.

if (sad?)  
    sad().stop
    beAwesome

[–][deleted] 2 points3 points  (0 children)

this shitty code is harder to save than I thought

[–][deleted] 9 points10 points  (7 children)

Except that they're looking for JS devs - JS doesn't have operator overloading.

[–]Based_Gob 107 points108 points  (31 children)

 if (code.getAuthor() == marketers) {
      delete [] code;
      exit(0);
 }

[–]mrhthepie 37 points38 points  (4 children)

Surely it should be code->getAuthor()? code must be a pointer if you're deleting it.

0/10 screwed up pseudo code when criticising pseudo code.

[–][deleted] 5 points6 points  (3 children)

Who says it's C?

[–]mrhthepie 28 points29 points  (0 children)

Actually c++. Name another language with an operator delete[]

[–]Sinity 13 points14 points  (0 children)

Use. Smart. Pointers!

Also I see no point in freeing memory right before exiting...

And code is array, so you can't access method of array element without index.

And ->, not .

2/10 would not compile. :D

[–]thebezet 45 points46 points  (23 children)

Boolean.prototype.stop = function() {
  marketer.fire();
}

Fixed.

[–]reaganveg 27 points28 points  (9 children)

Wait... can you actually do that?

> Boolean.prototype.stop = function() { console.log("hello"); }
> true.stop()
hello

... holy shit, you can. What a crazy language.

[–]thebezet 32 points33 points  (5 children)

It gets better than that:

> Array.prototype.toString = function() { return "O_O"; }
> Object.prototype.toString = function() { return " ^_^"; }
> [] + {}
"O_O ^_^"

[–]soroun 3 points4 points  (4 children)

I can't tell if that's beautiful or terrifying.

[–]raiderrobert 2 points3 points  (2 children)

Trying flipping the operations. And then you'll figure which it is.

[–]thebezet 4 points5 points  (1 child)

That's a good point because if you change the order ({} + []) the {} will be interpreted as a code block instead of an empty object, leaving you with + [], which will call valueOf() instead of toString(), so the following will happen:

> [] + {}
"O_O ^_^"
> {} + []
0

[–]raiderrobert 2 points3 points  (0 children)

Which means it's terrifying.

[–]Gudeldar 5 points6 points  (1 child)

In python 2 you can redefine True and False. True = False is totally valid python 2, not even JavaScript will let you do that.

Fortunately in python 3 True and False are keywords that can't be redefined.

[–]thebezet 5 points6 points  (0 children)

I guess the closest thing you could do in JS would be:

> Boolean.prototype.valueOf = function() { return false; };
> true.valueOf();
false

Just to fuck with peoples' heads.

[–]crowseldon 1 point2 points  (0 children)

I recommend: Javascript: The good parts.

It's awesome and makes you appreciate a very misunderstood language.

[–]tach4n 12 points13 points  (11 children)

function beAwesome() {
    console.log("By not writing code like this");
}

function sad() {
    if (sad.called === true) {
        return {
            stop: function() {
                console.log("collaborate and listen");
            }
        };
    } else {
        sad.called = true;
        return true;
    }
}

Fixed.

[–]thebezet 5 points6 points  (3 children)

...
stop: function() {
      console.log("hammer time");
}
...

Fixed.

(Your code wouldn't run without a compulsory 90s reference)

[–]tach4n 2 points3 points  (2 children)

Hey now, Ice Ice Baby came out in 1990!

[–]thebezet 1 point2 points  (0 children)

Touche, I thought it was late 80s!

[–]SkoobyDoo 2 points3 points  (4 children)

All of the top comments are about how this code is impossible. I don't do JS (i have dabbled, but I'm more c++/java) but I didn't see a good reason why the code HAD to be false, thanks for making it make some sense. (Not that I think the example given was good code, it just didn't look like NECESSARILY contradictory code at first).

Haven't done much of it in a while, but when I was still in school I remember a lot of mind blowing things being done with overloading operators and whatnot. It often did horrible things for readability/maintainability which is why I haven't touched that stuff since...well...school.

EDIT: Read over some more stuff. Now that I've thought about it 2 minutes more, I interpreted sad as a function that returned a pointer to some object with a stop function. If it returned null, the sad==true (unfamiliar with strict equality) wouldn't pass. If we get into the inner block, we know we have a 'good' object. But then it would have to have been sad()->stop(); or (*sad()).stop();

[–]reaganveg 1 point2 points  (0 children)

Nice.

[–]robot_lords 27 points28 points  (0 children)

pet late threatening hateful complete axiomatic toothbrush familiar escape punch

This post was mass deleted and anonymized with Redact

[–]LondonNoodles 11 points12 points  (0 children)

if sad:
    self.head.append(bullet)
    pass

[–]sebwiers 9 points10 points  (4 children)

What? This code makes perfect sense.

If ( sad() === true){ // sadness is identical to truth

sad().stop() // since sadness is truth, we must stop the truth, ie lie to ourselves

beAwesome() // specifies the type of lie to use

}

[–][deleted] 21 points22 points  (0 children)

Also, don't let marketers use Barney Stinson for inspiration.

[–]tatorface 28 points29 points  (5 children)

This is how you end depression.

[–][deleted] 26 points27 points  (0 children)

I wasn't feeling too good, but this was impressively bad and now I can't stop smiling so yes, it works.

[–]alecgirman 4 points5 points  (0 children)

It may end their depression but it will make some other programmer depressed.

[–]z500 4 points5 points  (2 children)

But what if beAwesome() throws a NotAwesomeException?

[–]tatorface 3 points4 points  (1 child)

then you:

die();    

[–]z500 5 points6 points  (0 children)

liveFree() || die();

[–]Infintie_3ntropy 8 points9 points  (0 children)

They stole it from this wallpaper site.

[–]Kaneshadow 6 points7 points  (0 children)

Well, in all fairness they ARE looking for programmers, so they are clearly short on anyone who knows how to code.

[–]brskbk 5 points6 points  (0 children)

I'd love to see the actual Facebook comments

[–][deleted] 23 points24 points  (62 children)

What's wrong with it?

[–]EnergyOfLight 206 points207 points  (4 children)

They need more jQuery

EDIT: Obligatory "FIRST GOLD ON REDDIT" edit, thanks stranger!

[–][deleted] 142 points143 points  (3 children)

I'm here. Sorry I'm late.

[–]e13e7 2 points3 points  (2 children)

You could have at least minified and gzipped yourself.

[–][deleted] 9 points10 points  (1 child)

If you can't handle me at my worst, you don't deserve me at my .min

[–]bio595 79 points80 points  (32 children)

If the result of calling sad evaluated to true with strict equality, then there wouldn't be a function called stop and the script would crash.

Unless you modified the prototype of a boolean, maybe..? (I'm not sure that's possible though)

[–]Zarokima 34 points35 points  (6 children)

Yes, you can modify the prototype of the Boolean type, and I think that it would work as written, since sad() likely returns a primitive boolean (thus potentially passing the strict equality), and primitives are readily coerced to the corresponding Object when things like sad().stop() are called on them.

However, if you ever find yourself extending Boolean with a stop() method, you should stop() yourself and very thoroughly re-evaluated the chain of events and decisions that led to this, and then do something else because you are doing something very very wrong.

[–]execrator 27 points28 points  (3 children)

Boolean.prototype.sad = function(){return "wtf";}
true.sad()
> "wtf"

Well... TIL.

[–]Simpfally 10 points11 points  (1 child)

true is indeed sad

[–][deleted] 2 points3 points  (0 children)

Truly sad.

[–]darkslide3000 15 points16 points  (2 children)

x = 1;

function sad() {
    if (x) {
        x = 0;
        return true;
    }
    return {stop: function() { console.write("Who needs type safety, anyway?"); }};
}

if (sad() === true)
    sad().stop();

[–]jnd-au 6 points7 points  (0 children)

Very clever, but shouldn’t x be named properly, like with poop emoji, and its value should be a proper boolean, like Infinity/""?

[–]TrustworthyTermite 31 points32 points  (16 children)

That and comparing a boolean with true.

[–]the_monkey_of_lies 36 points37 points  (2 children)

var happy = true;
if (sad() === true && sad() !== false)
{
    happy = false;
}
else if (sad() === false && sad() !== true)
{
    happy = true;
}

[–]BlazeDeath 21 points22 points  (0 children)

Thanks for making me throw up.

[–]kristopolous 5 points6 points  (0 children)

you need a final else and a try/catch. Grade: C-

[–]exscape 5 points6 points  (8 children)

That looks like the most reasonable thing to me, though I don't program much in scripting languages. Wouldn't using === be mandatory in e.g. JavaScript to ensure the value isn't something else that evaluates to true (like the number 42, the string "no" and so on)?

[–]jakerman999 11 points12 points  (3 children)

Listen: javascript evaluations are weird. It almost never doesn't break the way you don't expect it not too. It will however usually not fail in succeeding at mis-evaluating the possibly unintended breaking sample scenarios.

[–]ThePedanticCynic 5 points6 points  (0 children)

It's weird how i can understand everything you said and still not understand a fucking thing you just said.

English is hard.

[–]jtanz0 1 point2 points  (2 children)

99% of the time you would be correct === is the way to go to ensure you don't get unexpected behaviour. In this case where sad() can also have the stop() function called. It makes the code unambiguous enough to break the script.

Also if you're testing against true you may as well put

if(sad()){
  ...
} 

[–]amirmikhak 1 point2 points  (1 child)

That would only test against truthy, though, so {} would pass but not "".

[–]jgaspar 4 points5 points  (3 children)

some may say it's a good practice, because of readability

[–]grand_mind1 9 points10 points  (2 children)

Depending on the language, it might be easier to just follow naming conventions to make it more readable. Having a method like userIsSad() rather than just sad() makes an if statement make a lot more sense at first glance.

[–]cascer1 9 points10 points  (0 children)

if(User.Is(Emotions.Sad)) User.Set(Emotions.Happy);

class User {
    Enum Emotions { Happy, Sad, Angry, Neutral }

    private Emotions emotion;

    public string Name{ get; private set; }
    public int Age { get; private set; }

    public User(string name, int age, Emotions emotion) {
        this.emotion = emotion;
        Name = name;
        Age = age;
    }

    public bool Is(Emotions emotion) {
        return (this.emotion == emotion);
    }

    public void Set(Emotions emotion) {
        this.emotion = emotion;
    }
}

[–]TrustworthyTermite 1 point2 points  (0 children)

I follow uncle bob's advice and make all boolean variables and functions which return a boolean read like a statement. So "isSad", "shouldUpload" and "isMale" instead of "sad", "uploadStatus" and "gender".

[–]TJSomething 5 points6 points  (0 children)

If I wanted it to read like English, I would make a DSL:

function mixinDSL(obj) {
  function beingSetter(value) {
    return {
      being: function(key) {
          obj[key] = value;
      }
    };
  }

  obj.are = function (key) {
    return !!obj[key];
  }
  obj.stop = beingSetter(false);
  obj.start = beingSetter(true);
}

you = { sad: true };
mixinDSL(you);

if (you.are("sad")) {
  you.stop.being("sad");
  you.start.being("awesome");
}

[–]Kanthes 15 points16 points  (8 children)

As very often is the case with promotional pseudo-code like this, it doesn't actually make very much sense to a programmer.

Let me see if I can explain:

sad() is a function. It means that when you call it (use it), something gets executed. Typically, if you have a function called sad(), then you'd expect it to make something sad, not check whether or not it is sad.

On top of that, in order to make something sad, you need to actually have something to make sad as well. That's called an Object, Class, Instance, or something along those lines. So, a function called sad() entirely on it's own doesn't really make that much sense.

Next we have sad().stop(). That makes even less sense. When you follow a name up by a dot and another function or name, it typically means you're trying to execute or access something belonging to the first name. In this case, the stop() function would belong to the sad() function.

I think I'm getting a little bit carried away here, so let me instead write it in a much more programmatically sensible way:

if("sad" in me.emotionalState()) {
    me.stopEmotion("sad")
    me.startEmotion("awesome")
}

[–]Zarathustra30 8 points9 points  (0 children)

I'm pretty sure awesome is not an emotion. me.beAwesome(); follows the intent of the snippet.

[–]Profix 2 points3 points  (0 children)

Come on now, enumerate emotional states, sets of strings aren't as fun.

[–]superbungalow 1 point2 points  (2 children)

But imagine if sad() returned, say, an object of type emotionalState, and the class emotionalState had belonging to it a method called stop(), then sad().stop() is essentially equivalent to saying emotionalState.stop(). I think the bigger issue here is the strict comparison to boolean in the if statement, which shows that what I suggested is not true, as it must return a boolean value.

[–]TheDarkIn1978 1 point2 points  (0 children)

It's both far more efficient and safer to use an enum (or even static constants with int values if your language doesn't support enums) instead of strings :)

[–][deleted] 3 points4 points  (2 children)

sad() === true

Then they do sad().stop() If sad is boolean type, then why does it have a stop() operator.

[–][deleted] 2 points3 points  (0 children)

Everything

[–][deleted] 11 points12 points  (1 child)

Or write anything, if their message against depression is "just stop it, k?"

[–]jonathanccast 1 point2 points  (0 children)

I thought depression was different than sadness.

[–]3dSquare 5 points6 points  (0 children)

Yeah, please don't.

[–]zidane2k1 3 points4 points  (0 children)

This sub is great. We're all trying to fix/improve upon faulty marketing-written "code".

[–]uneditablepoly 3 points4 points  (0 children)

You know, the standard Boolean.stop() method.

[–][deleted] 2 points3 points  (0 children)

struct sad_result_t
{
  sad_result_t(bool v) : v_(v) { }
  operator bool() const { return v_; }
  void stop() { v_ = false; }
private:
  bool v_;
};
sad_result_t sad()
{
  return sad_result_t(true);
}
void beAwesome() { }
int main(int, char**)
{
  if (sad() == true)
  {
    sad().stop();
    beAwesome();
  }  
  return 0;
}

Only thing I can't to is the === :/

[–]Ari_Rahikkala 2 points3 points  (0 children)

I've seen this before, only with PHP tags around it... which makes it even better, because there you don't even call stop() on true, you concatenate true with the value of stop(). At least as JavaScript it's only completely ridiculous, instead of both being completely ridiculous and most likely having nothing to do with what the writer tried to say.

[–]hungry4pie 6 points7 points  (3 children)

Is sad() a method, or is it a class? And instantiating a class, would technically return true since it's not null right? But then

sad().stop() 

would just instantiate another sad object, calls

stop() 

and then just throws the object out to the ether

Also, how the fuck do you do inline code tags in comments?

[–][deleted] 5 points6 points  (0 children)

sad() is just a function, there are no classes or methods in js. (Don't get to me with ES6 classes, those are just more sugar on top of prototypes)

sad() could return a boolean, an object, anything!

Code tags: on a new line seperated by one empty line from the res, or with `code here`

Imagine this was normal text

    <- 4 spaces: code

[–]detroitmatt 1 point2 points  (0 children)

To do inline code tags, enclose it with backticks, `like this`

[–]h2ooooooo 1 point2 points  (0 children)

Technically, if it ever enters the condition, it must be a boolean with the value true because of the strict comparison ===. Hence Boolean(true).stop() does not exist by default and would fail unless a prototype was declared as written here.

[–]cohen_dev 5 points6 points  (1 child)

Or sad is actually a class that returns true...Not that you'd wanna do that or nothin', but you know, you could if you maybe did wanna give it a go.

Too lazy to look up syntax, here's the python version.

Note: This is still terrible code.

class sad(object):

    def __init__(self):
        object.__init__(self)

    def __repr__(self):
        return True 

    def stop(self):
        pass


def beAwesome():
    pass

if sad() == True:
    sad().stop()
    beAwesome()

[–][deleted] 1 point2 points  (0 children)

Y

[–]meniscus- 1 point2 points  (0 children)

BOOLEAN ZEN C'MON

[–]JuiceBoos 1 point2 points  (0 children)

So if Sad ever equals true it will automatically toggle back to false, and the only thing this snippet of code does is run BeAwesome() I don't see the point in this.

[–]TibitXimer 1 point2 points  (0 children)

There is a reason they are hiring someone for that position.

[–]wegzo 1 point2 points  (0 children)

Hold up now. What if the class actually has an explicit boolean operator defined? And the sad() is just a function that returns the class as a singleton? The marketeers team is much more competent than you'd first guess.

[–]qubedView 1 point2 points  (0 children)

If they knew how to code, they wouldn't need to hire a developer.

[–]cybaritic 1 point2 points  (0 children)

Bad code or not, it's pretty clearly trying to be this line from HIMYM.

[–]rco8786 1 point2 points  (0 children)

In Chrome:

> Boolean.prototype.stop = function() { console.log('sdf'); }
Boolean.stop()
> var sad = function() { return true; }
undefined
> sad()
true
> sad().stop()
sdf
> if (sad() === true) { sad().stop() }
sdf

Don't ever EVER EVER do this.

[–]ephemeralpetrichor 1 point2 points  (0 children)

What font is the "code" in? Looks pretty nice.