• emerald@lemmy.place
    link
    fedilink
    arrow-up
    57
    arrow-down
    1
    ·
    1 year ago

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

    • ☆ Yσɠƚԋσʂ ☆@lemmy.mlOP
      link
      fedilink
      arrow-up
      25
      arrow-down
      12
      ·
      1 year ago

      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
        link
        fedilink
        arrow-up
        14
        ·
        1 year ago

        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
        
        • ☆ Yσɠƚԋσʂ ☆@lemmy.mlOP
          link
          fedilink
          arrow-up
          6
          arrow-down
          6
          ·
          1 year ago

          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
            link
            fedilink
            arrow-up
            4
            ·
            1 year ago

            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.

            • ☆ Yσɠƚԋσʂ ☆@lemmy.mlOP
              link
              fedilink
              arrow-up
              2
              arrow-down
              8
              ·
              1 year ago

              Sure, you end up passing higher order functions around, and my point is that complexity obviously goes up. There’s a reason callback hell is a well known thing in Js land. Meanwhile, Js is single threaded from user perspective. The fact that there is a background rendering thread in client side js is completely tangential to the discussion.

              Finally, the problem with callbacks is generally seen in server-side Js runtimes. A great example is if you have an HTTP handler that needs to get data from a db. In a language with user accessible threads you just make a db operation synchronously and return the result. In Js, you have to do a callback. The reason you can do the operation synchronously when you have threads is due to the fact that HTTP handler thread can accept a request and then dispatch a new thread to handle it while waiting for other requests.

              • Tartas1995@discuss.tchncs.de
                link
                fedilink
                arrow-up
                2
                ·
                1 year ago

                It is not really tangential to the discussion. You claimed it is because Js single threaded. Also it is not single threaded from the “users” perspective if you mean the developer. There are workers.

                If your issue is asynchronous function calls, just call synchronous functions. You might be stuck in a while loop somewhere but if you prefer that, use it. There are sync functions for everything in Js and/or you can easily create them yourself.

                • ☆ Yσɠƚԋσʂ ☆@lemmy.mlOP
                  link
                  fedilink
                  arrow-up
                  2
                  arrow-down
                  8
                  ·
                  1 year ago

                  Js is single threaded from user perspective. You have no access to the threading runtime as a user and cannot spawn a thread in Js to do some background work. Workers are a recent addition, but using them is quite different from what I’m talking about.

                  And being stuck in a while loop is precisely why people have to use callbacks and why all the APIs are async. This is literally the problem. If you’re dealing with any non trivial load, you are forced to use async mechanics.

    • Blackmist@feddit.uk
      link
      fedilink
      English
      arrow-up
      5
      ·
      1 year ago

      I prefer a bunch of

      if (fucked_up) {return(error_code);}

      for checking common errors.

      • DWin@sh.itjust.works
        link
        fedilink
        arrow-up
        2
        ·
        1 year 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.

      • vettnerk@lemmy.ml
        link
        fedilink
        arrow-up
        6
        ·
        edit-2
        1 year ago

        I’ll let Randall Munroe decide that himself, considering the fact that he provides URLs for hotlinking below the comics

        • bdonvr@thelemmy.club
          link
          fedilink
          arrow-up
          7
          ·
          1 year ago

          I don’t mean the act of embedding or direct linking in general, but in link aggregators these comics are well known for their alt text, which cannot be seen from the direct link.

          I think a good practice might be embedding the comic directly in your comment along with a “source” link.

          • McSinyx@slrpnk.net
            link
            fedilink
            English
            arrow-up
            3
            arrow-down
            1
            ·
            edit-2
            1 year ago

            these comics are well known for their alt text

            It’s title text, or in web comic circles, hover text. The linked comic’s alt is simply Lisp Cycles.

  • thejevans@lemmy.ml
    cake
    link
    fedilink
    arrow-up
    25
    arrow-down
    1
    ·
    1 year ago

    I know it’s not nearly as nested as this, but nesting in Rust annoys the hell out of me.

    impl {
        fn {
            for {
                match {
                    case => {
                    }
                }
            }
        }
    }
    

    is something I’ve run into a few times

    • darcy@sh.itjust.works
      link
      fedilink
      arrow-up
      1
      ·
      1 year ago

      the loop or match statement could possibly be extracted to another function, depending on the situation. rustc will most likely inline it so its zero cost

    • DWin@sh.itjust.works
      link
      fedilink
      arrow-up
      1
      ·
      edit-2
      1 year ago

      Just use this syntax

      let myResultObject = getResult() 
      let item = match myResultObject {
      	Ok(item) => item, 
      	Err(error) => {
      		return;
      	} 
      };
      
      • thejevans@lemmy.ml
        cake
        link
        fedilink
        arrow-up
        2
        ·
        1 year ago

        How does that change anything? Sorry if it wasn’t clear, this was assuming a function call in the for loop that returns either a Result or enum.

        • DWin@sh.itjust.works
          link
          fedilink
          arrow-up
          1
          ·
          1 year ago

          Oh sorry, I misread what you typed and went on a tangent and just idly typed that in.

          One thing you could do for your situation if you’re planning on iterating over some array or vector of items is to use the inbuilt iterators and the chaining syntax. It could look like this

          let output_array = array.into_iter()
              .map(|single_item| {
                  // match here if you want to handle exceptions
              })
              .collect();
          

          The collect also only collects results that are Ok(()) leaving you to match errors specifically within the map.

          This chaining syntax also allows you to write code that transverses downwards as you perform each operation, rather than transversing to the right via indentation.

          It’s not perfect and sometimes it’s felt a bit confusing to know exactly what’s happening at each stage, particularly if you’re trying to debug with something mid way through a chain, but it’s prettier than having say 10 levels of nesting due to iterators, matching results, matching options, ect.

          • thejevans@lemmy.ml
            cake
            link
            fedilink
            arrow-up
            1
            ·
            1 year ago

            I definitely use that syntax whenever I can. One of the situations where I get stuck with the nested syntax that I shared is when the result of the function call in the for loop affects the inputs for that function call for the next item in the loop. Another is when I am using a heuristic to sort the iterator that I’m looping over such that most of the time I can break from the loop early, which is helpful if the function in the loop is heavy.

            • DWin@sh.itjust.works
              link
              fedilink
              arrow-up
              2
              ·
              edit-2
              1 year ago

              It feels like maybe this could be a code structure issue, but within your example what about something like this?

              fn main(){
                  let mut counter = 0;
                  let output_array = array.into_iter()
                      .map(|single_item| {
                          // breaks the map if the array when trying to access an item past 5
                          if single_item > 5 {
                              break;
                          }
                      })
                      .collect()
                      .map(|single_item| {
                          // increment a variable outside of this scope that's mutable that can be changed by the previous run
                          counter += 1;
                          single_item.function(counter);
                      })
                      .collect();
              }
              

              Does that kinda syntax work for your workflow? Maybe it’ll require you to either pollute a single map (or similar) with a bunch of checks that you can use to trigger a break though.

              Most of the time I’ve been able to find ways to re-write them in this syntax, but I also think that rusts borrowing system although fantastic for confidence in your code makes refactoring an absolute nightmare so often it’s too much of a hassle to rewrite my code with a better syntax.

  • wim@lemmy.sdf.org
    link
    fedilink
    arrow-up
    12
    ·
    1 year ago

    Back when I was still in school, I ran a few tests on real world LISP and Java (the then dominant language, this was in the late days of Sun Microsystems succes).

    Turns out most LISP programs had fewer parentheses then Java had braces, parens and brackets.

  • YurkshireLad@lemmy.ca
    link
    fedilink
    English
    arrow-up
    7
    arrow-down
    5
    ·
    1 year ago

    I learned Lisp at uni and hated it. Thankfully that was long enough ago that I’ve forgotten everything I learned about it.

      • addie@feddit.uk
        link
        fedilink
        arrow-up
        13
        ·
        1 year ago

        Yeah - pure functions and immutable data aren’t always the right answer, but appreciating that they’re damn good most of the time is a good first step. Writing obvious code that does exactly what it appears to do at first glance and not one thing more? Your colleagues will thank you when they have to work with your stuff.