Hacker News new | past | comments | ask | show | jobs | submit login

I think the major problem with this is scope. Now a variable declared at the top of your function is in scope for the entire function.

Limiting scope is one of the best tools we have to prevent bugs. It's one reason why we don't just use globals for everything.




You can artificially create scope. I often write code like:

    Foo f = null;
    {
      ... stuff with variables
      f = barbaz;
    }


Is the point that any var declared in between the braces automatically goes out of scope, to minimize potential duplication of var names and unintended behavior ?

The worst I've seen is old school C programmers who insisted on reusing loop variables in other loops. Even worse, those loop variables were declared inside the loop declaration, which old C standards allowed to visible outside of it.

So they would have stuff like this

  for(int i=0; i<10; i++) { ... }
  for (;i<20;i++) { ... } 
Later versions of C++ disallowed this, which led to some interesting compile failures, which led to insistence of the old stubborn programmers that new compilers simply not be used


Now you have to make `f` nullable and you run the risk of not initialising it and getting a null pointer.

You can't do it in C, but in functional style languages you can do this:

  let f = {
    let bar = ...;
    let baz = ...;
    let barbaz = ...;
    barbaz
  };
Which is a lot nicer. But if you ask me it's just a function by another name except it still doesn't limit scope quite as precisely as a function.


In C++ you can do:

   auto f = [&] {
      ...
      return barbaz;
   }();
with the side benefit that you can also make the use of state explicit inside of [] instead of using wildcard capture.

Given that it's neither reused nor parametrized, I'm not sure why you see this kind of pattern as a "function by another name", though. Semantically it's more of a namespace if anything.


That literally is a function. I guess the important difference is you can easily confirm by inspection that it is only called once?

If that's an important property maybe it would be worth supporting an annotation on normal functions to enforce that. I guess you could easily write a linter for that.


Syntactically it is, but semantically it's really more of an isolated block IMO because not only it's called only once, but that call happens immediately (so no back-and-forth control flow unlike regular functions), and the lambda is not passed anywhere as a value either.


GCC and clang (and maybe others) have 'statement expressions': https://godbolt.org/z/sqYnbh4Ej




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: