3 ms·
This is why I think it's a mistake that many popular languages, including standard c/c++, do not support nested function definitions. This for me is the happy m
by norir 2y ago
This is why I think it's a mistake that many popular languages, including standard c/c++, do not support nested function definitions. This for me is the happy medium where code can be broken into clear chunks, but cannot be called outside of the intended scope. A good compiler can also detect if the nested function is only called once and inline it.
- badmintonbaseba 2y agoC++ has lambdas and local classes. Local classes have some annoying arbitrary limitations, but they are otherwise useful.
- knodi123 2y agoAfter spending a lot of time writing idiomatic React components in es6, I've found my love of locally declared lambdas to really grow. If I give the lambdas really good names, I find that the main body of my component is very, very readable, even more so than if I'd used a more traditional style liberally sprinkled with comments.
- zelphirkalt 2y agoGiving your lambdas names defeats part of their purpose though.
- int_19h 2y agoThey have two distinct purposes: anonymous functions, and closures. Those often go together, but there are many scenarios where you only care about the latter, and don't actually need the former. Named lambdas (i.e. lambdas assigned to local consts) covers this case if the language doesn't have dedicated syntax for it.
- knodi123 2y agomaybe one purpose. but it fulfills another purpose- self-documenting code, and a really simple non-nested main body to your function.
- marcosdumay 2y ago> If I give the lambdas really good names That's a really funny way to say it.
- humanfromearth9 2y agoIn Java, a local function reference (defined inside a method and never used outside of this method ) is possible. Notre that this function is not really tied to an object, which is why I don't call it a method, and I don't use the expression "method reference", it is just tired to the function that contains it, which may be a method - or not.
- kccqzy 2y agoCode can always be called outside of that scope just by returning function pointers or closures. The point is not to restrict calling that code, but to restrict the ability to refer to that piece of code by name. As mentioned by others, C++ has lambdas. Even if you don't use lambdas, people used to achieve the same effect by using plenty of private functions inside classes, even though the class might have zero variables and simply holds functions. In even older C code, people are used to making one separate .c file for each public function and then define plenty of static functions within each file.