this post was submitted on 24 Sep 2023
210 points (93.0% liked)

Programmer Humor

31998 readers
705 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 5 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
[–] emerald@lemmy.place 56 points 11 months ago (3 children)

If your code is that deeply nested, surely something has gone horribly wrong, yes?

[–] yogthos@lemmy.ml 12 points 11 months ago (1 children)

Problem is that Js kind of encourages this being single threaded and using callbacks for anything blocking. To be fair, the new async syntax sugar helps in modern Js, but nesting a bunch of callbacks or promises was basically the way you did stuff for the longest time.

[–] Tartas1995@discuss.tchncs.de 14 points 11 months ago (1 children)

Yes and no. Any programming language encourages nesting as in the end the computer does nest your code. So it is only normal and predictable that languages would reflect that. BUT! Nest logic can often be inverted and by doing so, reduce how much nesting you need to do.

If (data is not null) {
    If (data has field x) {
         Return data x
    } else return null
} else return null

Can be

If (data is null) return null
If (data hasn't field x) return null
Return data x
[–] yogthos@lemmy.ml -1 points 11 months ago (1 children)

I'm not arguing that avoiding deep nesting is a good idea, or that techniques foe doing that don't exist. I'm just pointing out that Js style programming naturally leads you to nesting things because of the nature of callbacks. Notice how your example isn't using callbacks.

[–] Tartas1995@discuss.tchncs.de 4 points 11 months ago (1 children)

Yeah and you can void nesting there just as easily and you have the same issues in any other programming language. You just need to create functions. Also JavaScript is not single threaded... you only have access to the dom on one thread, for obvious reasons.

Please explain to me how you do e.g. file downloads without a callback in your favorite language. If you solution involves having the main thread being stuck in a while loop, I am not sure if your complain about nested code can be taken seriously.

[–] h_a_r_u_k_i@programming.dev 10 points 11 months ago

Code aesthetic: If your code looks like a triangle, you're seriously doing something wrong.

[–] Blackmist@feddit.uk 5 points 11 months ago (1 children)

I prefer a bunch of

if (fucked_up) {return(error_code);}

for checking common errors.

[–] DWin@sh.itjust.works 2 points 11 months ago

Yup, never nest.

All the conditions should be checked and returned if they failed as you go through the function with the successful response being the last line.