An unofficial, read-only Hacker News reader. Join the beta →

2035 came early (opens external site)

1037 points by setheron 4 days ago | fzakaria.com | 382 comments on HN

View full thread · View on Hacker News

Comment thread (6)

  1. In JS? What aspects of RAII can you simulate, and how?
    Replies (1)
    1. I was talking in general, not JS specific, especially since JS has global namespace, note my second paragraph.

      In any case, you have two ways to do something similar, kind of.

          function with_file(filename, operation_fn) {
             let resource = null;
      
             try {
               resource = open_resource(filename);
               return operation_fn(resource);
             } finally {
                resource?.close()
                 }
          }
      
          with_file("/my/path/something", (fd) => {
              let data = fd.read_something()
              // handle data
          })
      
      Naturally there are multiple variations thereof, on how to handle errors, or which way to parameterise how to close resources.

      Then we have the C# inspired way,

          using fd = open_resource("/my/path/something")
          let data = fd.read_something()
          // handle data
      
      
      And if open_resouce doesn't support using declaration, an helper builder function can be used to wrap it in such a type.

      Yes it isn't as automatic as pure RAII, but it gets close enough for most practical purposes.

      Replies (2)
      1. Giant problem with the first approach is continue, break, return keywords can't be used (or even worse, has different semantics in case of `return`).
        Replies (1)
        1. Yeah, again the remark on how this is better suited for FP and LP languages.

          Which besides not having global variables, also don't do continue, break, return.

          The first approach traces back to how resource management was initially done in Lisp languages, alongside conditions.

      2. This matches the case of a lexically scoped variable and no moves. With full RAII, the resources are tracked across their entire dynamic lifetime, not just one lexical block, allowing them to be returned to callers, placed in containers, etc.
        Replies (1)
        1. Not really when taking heap into account, while having the code storage agnostic, which is why you need helper classes like handles or std::unique_ptr, with move semantics, otherwise the RAII story gets rather complicated.