Why we need functions as first class citizens?
I had been following the debate on inclusion of closures into Java for a long time. And I used to wonder, why do I need them. I understand that functions are important, but cant we achieve that almost entirely though the use of interfaces. I think I have realized why we need functions to be first class citizens, and it has more to do with restricting scope over which the function will be available.
Lets start with a simple scenario highlighting the need for data to be a first class citizen. You are doing some complicated calculation which takes time and is error-prone to write. In most cases, if you need to repeat it exactly, you would store it in a local variable, so that it can be reused. This comes very naturally to us, and most of the times we dont notice what we have exactly done. We have restricted the scope of the partial calculation by declaring a local variable, and we can further restrict its access by defining a logical block. This would not have been possible if data was not a first class citizen. We would have had to rewrite the whole calculation again or we could define a function for the calculation. But if we define a function for it, then it is almost impossible to restrict the scope of the function.
Now consider the dual of the above situation, we wrote some functionality which is totally local to a function and needs to be repeated a couple of times. We cannot use interfaces for it, as then we can’t restrict the access to that method. Moreover, we can’t define a function locally inside the existing function since that would make function a first class citizen which it is not. Hence, the need for closures or the need for acknowledging the functions as first class citizens. As in that case, we can simply declare function in restricted scope and enable code reuse while abstracting away local implementations to avoid contaminating the namespace.



