r/badcode • u/Robinimus • May 04 '21
ruby Found this little snippet in the codebase today.
21
u/hiljusti May 04 '21
@no_products = ids.empty?
Assuming nothing is relying on a possibly nil return value...
16
u/Robinimus May 04 '21
It gets better, the only way @no_products gets used is like this
@no_products.present?2
u/hiljusti May 05 '21
Wait does that code even get used? None of
TrueClass,FalseClass, orNilClasshavepresent?defined. They'd raise aNoMethodError.(Unless this is Rails monkey-patching? or similar black magicks)
3
u/bikemowman May 05 '21
Not OP, but yeah
present?is from ActiveSupport, which is included with rails. At least, I think that’s the case. So yeah, Rails monkey-patching.
14
6
u/SrineshNisala May 04 '21
How the hell people create these pretty looking code snippets anyway?
1
u/Robinimus May 04 '21
I was always wondering the same thing. Then I implemented the one skill I use every day; creative googling
33
u/MurdoMaclachlan public boolean isInt(int i) { return true; } May 04 '21
Image Transcription: Code
if ids.empty?
@no_products = true
return
end
@no_products = falseI'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
2
57
u/AL1L May 04 '21 edited May 04 '21
Other than it being pointless, this style is how I like writing my code. General rules I try to follow are,
minimize use of
else,NO nested
ifs,functions/methods should serve exactly one purpose,
and your expected "good" result should be last in the function/method.
I don't always follow these, like in cases of quick 2 min scripts, but even then I follow them to not build bad habits
26
u/Manny_Sunday May 04 '21
I agree completely. One of my biggest peeves is methods that look like
if(validCase) { //some stuff //return is buried and you have to find it } //handle invalid case //return at endIf youre just skimming through looking for something, the cases for when things return what are so hard to find. Easier when the method kind of marches down with time so you can read through it without needing to scroll up and down to figure out your cases.
18
May 04 '21
Ternary operator ftw
5
u/consultio_consultius May 04 '21
You’re getting downvotes but in some compilers it can actually be faster.
8
u/AL1L May 04 '21
I use it all the time, I used one literally 5 min ago for work, yeah idk why he's getting downvotes.
12
u/consultio_consultius May 04 '21
The comments in the sub are usually fucking awful. The guy above the person who commented is getting upvoted for some pretty inconsistent advice.
This type of stuff would never fly in any shop I’ve worked at.
-1
u/AL1L May 04 '21 edited May 04 '21
That comment was mine haha, not sure how it's inconsistent?
And they work pretty well, been following those for years. Have made pretty complex applications with those rules, they're not too hard to follow. I can't think of any good reasons not not follow them, you have any? The reason I follow them is it makes the code a lot easier to read.
Also what is a "shop"? A shop to me in programming sense is either a coding farm in India or some learning workshop.
Also also, wasn't giving advice, just saying what I do, didn't say it was better or worse than anything, it's just a comment, not like I was trying to provide an in-depth explanation of it
3
u/consultio_consultius May 04 '21 edited May 04 '21
If you write software like above, I'm not too sure how you can say that you follow the rules you laid out.
At the surface this function/method is simple. In actuality it isn't simple. While the function/method contract isn't present, it's pretty obviously creates side effects. I'll admit I don't know Ruby, but why would you have a voided return on what is an evaluation?
If you are going to not nest ifs -- it doesn't make any sense to void returns because then you can't even perform piping methods or function composition. If your expected 'good' return is at the bottom, how do you manage graceful and verbose error messaging, while still being 'readable'? You'll just end up with either a small block with not-so-great very generic throwing, or a large block with loads of information all before your method returns the 'good' result.
"Shops" -- just slang. Worked in web development companies while in undergrad, worked in embedded systems and communications software, a lab while in grad school, and now a lab/company these days.
7
u/AL1L May 04 '21
That literally makes no sense, can you provide examples?
At the surface this function/method is simple. In actuality it isn't simple. ... on what is an evaluation?
I think you're completely misinterpreting what I have said... It's kinda hard to judge the context considering we get only 5 lines of code. I said I code with those rules generally (which is about 90% of the time).
If you are going to not nest ifs -- it doesn't make any sense to void returns ... before your method returns the 'good' result.
I mostly work with Python, JS, Java, scripting stuff, Lua and similar languages, so for error handling you just raise/throw if a condition isnt met, once all your assertions are done, then you can do what you need to do instead of doing something like
if (my_condition) { // some setup code or something idk if (some_other_condition) { // I did it right! return good_boi; } else { // Else not really necessary in this case throw new MyErrorNum2("oh no, X went wrong"); } } else { // Else not really necessary in this case throw new MyErrorNum1("oh no, you are dumb"); }I would do something like this instead
if (!my_condition) throw new MyErrorNum1("oh no, you are dumb"); // some setup code or something idk if (!some_other_condition) throw new MyErrorNum2("oh no, X went wrong"); // I did it right! return good_boi;The latter is soo much easier to read and it reduces the complexity on the eyes and is just generally easier to follow and debug because there are less "banches". And afaik neither one of these has any meaningful performance benefit over the other.
That being said, I've also been doing a lot of Rust and for the most part I'm able to code in the same style as with other languages
1
u/consultio_consultius May 04 '21 edited May 04 '21
Why don't you use if/else if/else? Again -- that doesn't help readability when you just use if,if,if,if -- also it doesn't help with any compiler using branch prediction.
And if you're going to be throwing and not returning errors... maybe you should be using try/catch in your production code, especially when dealing with concurrency.
edit: Also you're a BIG BIG BIG liar or are absolutely bastardizing the things you work with -- if you're writing either Lua or Rust, you would know exactly why these patterns are poor and wrong.
2
u/ParanoydAndroid May 04 '21
Why don't you use if/else if/else? Again -- that doesn't help readability when you just use if,if,if,if --
It does for me, and for most python developers because it's a standard pattern. Guard clauses and if/elif constructs have different semantics, and a series of "ifs" better communicates the semantics of the guard clauses.
also it doesn't help with any compiler using branch prediction.
This isn't really easy to know. Branch prediction is complicated, uses statistical inference, and is multiple.layers of abstraction away from the python code.
And anyway, python isn't crazily performant. Premature optimization is the root of all evil, and I'll take the semantically clearer code over an ambiguous shot at a small optimization.
Realistically, the vast, vast majority of python app optimization is in architecture and I/o. You're usually not running a microcontroller. So you're better off focusing effort there, not on trying to finesse the processor pipeline.
And if you're going to be throwing and not returning errors... maybe you should be using try/catch in your production code, especially when dealing with concurrency.
Depends entirely on architecture. I, for example, often have single-purpose utility functions and methods just throw and use a service layer or a decorator to collect and handle lower level exceptions.
→ More replies (0)1
u/AL1L May 04 '21
Here's some code I've written for a client (yeah I have permission to share it), here's a paste bin link if it's hard to read; https://pastebin.com/eHEYSk6u
async (req, res) => { await dbConnect(); const method = req.method.toUpperCase(); req.path = req.query[Model.modelName.toLowerCase()] || []; if (req.path.length > 1) { return res.status(404).send({ errors: ["Route not found"] }); } if (!allowMethods.includes(method)) return res.status(405).send({ errors: ["Invalid method (1)"] }); if (method !== 'GET') if (method === 'POST' && req.path.length === 1) { return res.status(405).send({ errors: ["Invalid method (2)"] }); } else if (method !== 'POST' && req.path.length === 0) { return res.status(405).send({ errors: ["Invalid method (3)"] }); } if (requestSecurity && !(await requestSecurity(req, res))) { return res.status(403).send({ errors: ["You are not authorized for this endpoint and/or method"] }) } switch (method) { case 'GET': return req.path.length === 0 ? await get(req, res) : await getOne(req, res); case 'POST': return await post(req, res); case 'PATCH': return await patch(req, res); case 'DELETE': return await deleteRecord(req, res); } return res.status(501).send({ errors: ["Method not implemented"] }); }And here it is rewritten as you say it should be (with nested ifs), tell me which one is easier to read
async (req, res) => { await dbConnect(); const method = req.method.toUpperCase(); req.path = req.query[Model.modelName.toLowerCase()] || []; if (req.path.length <= 1) { if (allowMethods.includes(method)) { if (method === 'GET' || (method === 'POST' && req.path.length === 1) || (method !== 'POST' && req.path.length === 0)) { if (!requestSecurity || await requestSecurity(req, res)) { switch (method) { case 'GET': return req.path.length === 0 ? await get(req, res) : await getOne(req, res); case 'POST': return await post(req, res); case 'PATCH': return await patch(req, res); case 'DELETE': return await deleteRecord(req, res); default: res.status(501).send({ errors: ["Method not implemented"] }); } } else { res.status(403).send({ errors: ["You are not authorized for this endpoint and/or method"] }) } } else { res.status(405).send({ errors: ["Invalid method (3)"] }); } } else { res.status(405).send({ errors: ["Invalid method (1)"] }); } } else { res.status(404).send({ errors: ["Route not found"] }); } }3
u/consultio_consultius May 04 '21 edited May 04 '21
You don’t use try catch in production? And i didn't say you should use nested ifs, I said you should use piping/composing. Your errors default to only one problem, and don't expose all problems. LOL -- AND THE KEY IS EVEN errors! You're literally only sending one!
Apparently you've never use else-if before, because the majority of your complaints of nesting ifs would be gone given the examples you've shown.
There's also just a huge issue with 'oh-it's-readable' versus, this mess is unmaintainable when specifications change. AND NEITHER OF THESE ARE READABLE.
WHAT are you doing calling an asynchronous func in an if evaluation???
THIS IS BAD CODE and I knew it would be given the tips you had originally posted.
Why isn't your db connection a singleton handled by your server instance?
WHY ARE YOU MODIFYING YOUR REQUEST AND NOT ACTUALLY PROVIDING ENDPOINTS?!?!? Holy smokes -- what ever lib you're are using will provide pathing for you.
-1
u/AL1L May 05 '21
I completely missed this comment
There's also just a huge issue with 'oh-it's-readable' versus, this mess is unmaintainable when specifications change. AND NEITHER OF THESE ARE READABLE.
readable to me and many others, idk man, it's preference anyways. The point of code is to explain to explain to the computer what you want it to do, if the human cant read it is pointless, might as well write machine code (joke). How is it not maintainable?
WHAT are you doing calling an asynchronous func in an if evaluation
What's wrong with that lol? has the same outcome if I were to not do that
THIS IS BAD CODE and I knew it would be given the tips you had originally posted.
alright lol
Why isn't your db connection a singleton handled by your server instance?
I explain this later, yeah you're right it should be, and I do that for most my other projects, but there are underlying reasons I couldnt and it wasnt worth my time.
what ever lib you're are using will provide pathing for you.
It does, and im using it. This code + other stuff makes it so I just have to drop in a few lines of code for a new Model and security and other stuff will be handled for any Model in the database.
5
1
u/lochness_ripcord May 04 '21
hate to be that guy, but what theme/color scheme is this?
1
u/Robinimus May 04 '21
Haha, good question, I just picked the preset for ruby on carbon. Nightcrawler maybe?
2
May 05 '21
I have no idea what language this is; but I know ruby syntax is sort of pythonic, but at the same time, rather perplexing. So if I had to guess, I'd say ruby.
edit: I just read the flair... it is in fact ruby.
2
u/americk0 May 05 '21
Don't worry I did it too. I was guessing ruby and came to the comments to be sure. Didn't see the flair until you mentioned it
0
May 04 '21
[deleted]
7
u/Robinimus May 04 '21
I just googled code to image and this popped up: https://carbon.now.sh/
0
2
u/drago41212 May 04 '21
Search for carbon on google
Edit: carbon.now.sh (realised carbon won’t bring it up lol)
0
May 04 '21
[deleted]
2
u/Robinimus May 04 '21
Yep, sometimes easier than trying to convince people.. we finally have rubocop and reek running with overcommit and rfix, so it'll get flagged before it can get pushed now
1
u/recycle4science May 04 '21
At the very least they could return the result of the boolean expression!
1
u/AutoModerator May 04 '21
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/Korzag, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
You can find some examples in the reddit help documentation.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
140
u/oldcastor May 04 '21
Its bad only if there is no more code after false, early exit is a good practice