r/badcode • • May 04 '21

ruby Found this little snippet in the codebase today.

Post image
687 Upvotes

87 comments sorted by

140

u/oldcastor May 04 '21

Its bad only if there is no more code after false, early exit is a good practice

1

u/throwaway8u3sH0 May 07 '21

Debatable. In Ruby and Python, yes. In Scala, definitely not.

-20

u/Willinton06 May 04 '21

I wouldn’t call it a good practice, it’s a double edge sword, like everything else, it really depends on the situation

38

u/oldcastor May 04 '21

If you writing a single responsibility methods (which is doable most of the cases) and at some point can give the definitely explicit answer, I can't imagine situation where early exit can be harmful ( neither in case of application logic nor in case of readability ).

If you can show example I'd be very interested to look at it

-24

u/Lost4468 May 04 '21

Well a function should generally have at least 2,000 lines. Any less and you're just making your program slower by having to jump to all those functions.

27

u/TheKeenMind May 04 '21

what the fuck are you talking about

-12

u/Lost4468 May 04 '21

You shouldn't split up functions. It makes it so the computer has to scroll through the file to find where the function was, then continue. It makes code much slower. It's why it's best to have functions be as long as possible.

6

u/TheKeenMind May 04 '21

4

u/BenjaminGeiger May 04 '21

Poe's Law strikes again?

-6

u/Lost4468 May 04 '21

Not really. I agree with them, they're right. There really is a slowdown associated with not writing really long functions.

1

u/[deleted] May 16 '21

You can't be serious.

Edit: Ok, just read everything, you're not.

10

u/danbulant May 04 '21

To add to that:

Ifs require branching and jumps too, which are slow as well, so you don't want to use them.

/s

2

u/Eiim May 04 '21

Automatic compiler inlining, anyone?

13

u/Hozerino May 04 '21

I laughed at that, but then I was afraid it wasn't irony

3

u/b1ack1323 May 05 '21

You shouldn't even have files that have 2,000 lines. Functions should be small, 100 lines is a rule of thumb.

3

u/hermthewerm00 May 05 '21

I always heard 40

1

u/Manny_Sunday May 05 '21

Back in school, one prof had us docked a mark for every line after 40 in a single function, and a mark whenever a line was longer than 80 chars 😂

At least he gave us a style linter that highlighter all your problems though.

Also marks docked for magic numbers other than 1, -1, 0.

1

u/Lost4468 May 05 '21

and a mark whenever a line was longer than 80 chars 😂

This one is ridiculous these days. There's no need to enforce such a small line limit when even the smallest monitors can fit way more on, and more importantly every single IDE and text editor out there can easily text wrap code.

Don't get me wrong I still stick to it in python (although the norm is 88 there), because it generally just works out well in python. But in other languages like C# enforcing such a small line length limit can actually decrease code readability.

80 is arbitrary, I think a better way to do it in the modern world is just to judge it line by line. Having to break up a line because your code is 85 characters long is the most ridiculous thing. When you have to do that just putting 85 characters in is normally the best option. Putting a hard limit doesn't make any sense, and it also makes some people think purposely stacking multiple things onto one line is ok so long as it's under 80 characters, when it's often important that a line is only say 40 characters...

A better rule is just that each line should be responsible for a single operation. Not a literal operation, e.g. writing a maths formula on one line is not only fine, it's generally better.

mark for every line after 40 in a single function

This one is slightly better, as it's generally very rare you have to have that many lines in a function. But I still think having a specific limit is arbitrary. You should be aiming more at an ideal rather than an arbitrary number of lines. There are situations where more than 40 is warranted, and similarly sometimes having 35 lines is way too many. Generally a better rule is "each function should do one thing only".

2

u/Arheisel May 05 '21

I just write an entire module in a single linq query

1

u/Lost4468 May 05 '21

You shouldn't even have files that have 2,000 lines.

That depends on who you ask. Python developers do it all the time. I don't think you should either (the original comment was obviously a joke, I don't know how the sub took it seriously), but it's very common and suggested by many.

Functions should be small, 100 lines is a rule of thumb.

There's virtually never a need to have 100 lines in a function. You really don't need more than ~30-40.

4

u/beclops May 04 '21

That's super dumb

1

u/Godzila543 May 05 '21

Nuked for being funny, reddit is so dumb

-39

u/Robinimus May 04 '21

Oh definitely, an early return is perfectly fine. The way to do it is just

return if ids.empty?

and i forgot to add the line where the products actually just get returned, so @no_products is completely useless because @products.any is also false haha

59

u/jgdeece May 04 '21

Your suggestion doesn’t do the same thing as this code though, unless there’s nothing more to the method. Feels like there’s a bit more missing to understand how this is bad.

-17

u/Robinimus May 04 '21

I'm not sure I'm to share all the nitty gritty details of the chuck. It was a lot worse than just this snippet.

30

u/altermeetax May 04 '21

Well then just upload that as well

5

u/xXLeoXxOne May 04 '21

I only do stuff like this after optimizing etc. for programming its way easier in the other form

-13

u/Robinimus May 04 '21

This has been up and running for the last 4 years, haha

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, or NilClass have present? defined. They'd raise a NoMethodError.

(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

u/DelishMango May 04 '21

What language is this

14

u/Robinimus May 04 '21

Ruby (on rails)

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 = false

I'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

u/[deleted] May 04 '21

[removed] — view removed comment

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 end

If 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

u/[deleted] 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

u/AtheRipper May 04 '21

There are no products, you are receding.

3

u/beclops May 04 '21

Comfortably Null

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

u/[deleted] 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

u/[deleted] 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

u/[deleted] May 04 '21

[deleted]

1

u/[deleted] May 05 '21

to anyone interested, the exact extension I mentioned is Code Snap

2

u/drago41212 May 04 '21

Search for carbon on google

Edit: carbon.now.sh (realised carbon won’t bring it up lol)

0

u/[deleted] 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.