Is every function a closure? - closures

Just wondering, since closure is a function that has references to variables/methods outside it's definition.
Every function closes over program's global variables (basically in every mainstream language, be it javascript/python/c/c+/whatever).
So, consequently, every function is a closure?
Edit: let me reemphasize, I'm not talking only about closures in javascript but in a more general context

Yes, exactly. As you've identified, every function in JavaScript is a closure over at least one context: The global context. That's how/why global variables work in JavaScript.
We don't normally call them closures unless they close over some other context and actually make use of the fact that they do, but you're quite right that at a technical level, they all are.
Every function closes over program's global variables (basically in every mainstream language, be it javascript/c/c+/whatever).
I wouldn't generalize that far, no. Different languages have different ways of implementing global variables. Whether functions in those languages are all "closures" is probably open for debate, so I've restricted my answer above to JavaScript.

closure is a function that has references to variables/methods outside its definition
No, this is a "function with free variables", not a "closure".
To quote wikipedia
...a closure is only distinct from a function with free variables when outside of the scope of the non-local variables, otherwise the defining environment and the execution environment coincide and there is nothing to distinguish these (static and dynamic binding can't be distinguished because the names resolve to the same values).
In other words, in some context, a closure is a reference to a function that binds variables from another context. Otherwise, it wouldn't make sense to call it a "closure".

Related

Why is using final, with no type, considered good practice in Dart? ie `final foo = config.foo;`?

I see this recommended in the dart style guide, and copied in tons of tutorials and flutter source.
final foo = config.foo;
I don't understand it, how is this considered best practice when the readability is so poor? I have no clue what foo is here, surely final String foo = config.foo is preferable if we really want to use final?
This seems the equivalent to using var, which many consider a bad practice because it prevents the compiler from spotting errors and is less readable.
Where am I wrong?
In a lot of cases is does not really matter what type you are using as long the specific type can be statically determined by the compiler. When you are using var/final in Dart it is not that Dart does not know the type, it will just figure it out automatically based on the context. But the type must still be defined when the program are compiled so the types will never be dynamic based on runtime behavior. If you want truly dynamic types, you can use the dynamic keyword where you tell Dart "trust me, I know what I am doing with this types".
So types should still be defined where it matter most. This is e.g. for return and argument types for methods and class variables. The common factor for this types is that they are used to define the interface for using the method or class.
But when you are writing code inside a method, you are often not that interested in the specific types of variables used inside the method. Instead the focus should be the logic itself and you can often make it even more clear by using good describing variable names. As long the Dart analyzer can figure out the type, you will get autocomplete from your IDE and you can even still see the specific type from your IDE by e.g. Ctrl+Q in IntelliJ on the variable if you ends up in a situation where you want to know the type.
This is in particular the case when we are talking about the use of generics where it can be really tiresome to write the full specific type. Especially if you are using multiple generics inside each other like e.g. Map<String, List<String>>.
In my experience, Dart is really good to figure out very specific types and will complain loudly if your code cannot be determined statically. In the coming future, Dart will introduce non-null by default, which will make the Dart compiler and analyzer even more powerful since it will make sure your variable cannot be null unless this is something you specifically want and will make sure you are going to test for null when using methods which are specified to not expecting null.
About "Where am I wrong?". Well, a lot of languages have similar feature of var/final like Dart with the same design principle about the type should still be statically determined by a compiler or runtime. And even Java has introducing this feature. As a experienced Java and Dart programmer I have come to the conclusion for myself that typing inside methods are really not that important in a lot of cases as long I can still easily figure out the specific type by using an IDE when it really matters.
But it does make it more important to name your variables so they are clearly defining the purpose. But I am hoping you already are doing that. :)

Arrow KT: Reader Monad vs #extension for Dependency Injection

I've read about Reader Monad from this article by Jorge Castillo himself and I've also got this article by Paco. It seems that both tackles the idea of Dependency Injection just in a different way. (Or am I wrong?)
I'm really confused whether I understand the whole Reader Monad and how it relates to the Simple Depenency Injection that Paco is talking about.
Can anyone help me understand these two things? Would I ever need both of them in one project depending on situations?
Your doubt is understandable, since yes both approaches share the same outcome: Passing dependencies implicitly for you all the way across your call stack, so you don't need to pass them explicitly at every level. With both approaches you will pass your dependencies once from the outer edge, and that's it.
Let's say you have the functions a(), b(), c() and d(), and let's say each one calls the next one: a() -> b() -> c() -> d(). That is our program.
If you didn't use any of the mentioned mechanisms, and you needed some dependencies in d(), you would end up forwarding your dependencies (let's call them ctx) all the way down on every single level:
a(ctx) -> b(ctx) -> c(ctx) -> d(ctx)
While after using any of the mentioned two approaches, it'd be like:
a(ctx) -> b() -> c() -> d()
But still, and this is the important thing to remember, you'd have your dependencies accessible in the scope of each one of those functions. This is possible because with the described approaches you enable an enclosing context that automatically forwards them on every level, and that each one of the functions runs within. So, being into that context, the function gets visibility of those dependencies.
Reader: It's a data type. I encourage you to read and try to understand this glossary where data types are explained, since the difference between both approaches requires understanding what type classes and data types are, and how they play together:
https://arrow-kt.io/docs/patterns/glossary/
As a summary, data types represent a context for the program's data. In this case, Reader stands for a computation that requires some dependencies to run. I.e. a computation like (D) -> A. Thanks to it's flatMap / map / and other of its functions and how they are encoded, D will be passed implicitly on every level, and since you will define every one of your program functions as a Reader, you will always be operating within the Reader context hence get access to the required dependencies (ctx). I.e:
a(): Reader<D, A>
b(): Reader<D, A>
c(): Reader<D, A>
d(): Reader<D, A>
So chaining them with the Reader available combinators like flatMap or map you'll get D being implicitly passed all the way down and enabled (accessible) for each of those levels.
In the other hand, the approach described by Paco's post looks different, but ends up achieving the same. This approach is about leveraging Kotlin extension functions, since by defining a program to work over a receiver type (let's call it Context) at all levels will mean every level will have access to the mentioned context and its properties. I.e:
Context.a()
Context.b()
Context.c()
Context.d()
Note that an extension function receiver is a parameter that without extension function support you'd need to manually pass as an additional function argument on every call, so in that way is a dependency, or a "context" that the function requires to run. Understanding those this way and understanding how Kotlin interprets extension functions, the receiver will not need to be forwarded manually on every level but just passed to the entry edge:
ctx.a() -> b() -> c() -> d()
B, c, and d would be called implicitly without the need for you to explicitly call each level function over the receiver since each function is already running inside that context, hence it has access to its properties (dependencies) enabled automatically.
So once we understand both we'd need to pick one, or any other DI approach. That's quite subjective, since in the functional world there are also other alternatives for injecting dependencies like the tagless final approach which relies on type classes and their compile time resolution, or the EnvIO which is still not available in Arrow but will be soon (or an equivalent alternative). But I don't want to get you more confused here. In my opinion the Reader is a bit "noisy" in combination with other common data types like IO, and I usually aim for tagless final approaches, since those allow to keep program constraints determined by injected type classes and rely on IO runtime for the complete your program.
Hopefully this helped a bit, otherwise feel free to ask again and we'll be back to answer 👍

How to name a function that produces a closure

I understand closures, even though I scarcely use them, but whenever I can squeeze one I have no idea of how to name it.
The best I can think of is sticking a "make" before what would be the name of the function:
function makeSortSelection(settings1, settings2) {
return function() {
/* sort stuff attending to settings1 and settings2 */
};
}
$("#sort-button").click(makeSortSelection('ascending',foo));
(I almost always use them in Javascript, but I guess this is a very language-agnostic question)
Sadly, most examples I found of closures just use "foo" or "sayHello". I like to give all my functions a verb as name: functions "do stuff", and their name reflects it ("sortSelection", "populateForm"). In the same spirit, how should I name closures, that "do things that do stuff"? What conventions do you use, and what are the most common?
PD: I tend to use Google's style guide when in doubt, but it says nothing about this.
Closures aren't nameable entities. Functions are nameable but a closure isn't a function.
Rather than define "a closure" it is easier to define the circumstances under which closure arises.
A (lexical) closure (in javascript) occurs and continues to exist as long a persistent external reference to an inner function exists, but neither the outer function nor the inner function nor the reference to the inner function is, in itself, a closure. Pragmatically speaking, a closure is a construct comprising all these elements plus a feature of the language by which garbage collection is suppressed when they exist.
In my opinion it is wrong, as some claim, that "all functions are closures". Yes, all functions have a scope chain, but a closure should only be regarded as existing once an outer function has completed and returned, and a persistent reference to an inner function exists.
By all means give the returned function a verb-based name, just like any other named function - there's no need to regard it differently just because it is was returned by another function. In every respect the returned function is just a function - it just happens to be a function with access to the scope chain of the (execution context of the) outer function that brought it into being - nothing more than that.
EDIT:
I just realised I didn't address the critical point of the question - rephrased "how to name a function that exists for the express purpose of forming a closure by returning a function".
Like you, I have a problem here.
Most often I use the "make" prefix, as in your example. This seems to be best most of the time.
I have also used "_closure" as a suffix, This doesn't obey the "verb rule" but has the advantage of being independent of natural language. "Make" is strictly an English word and speakers of other languages will probably choose to use their own "faire", "machen" etc. On the other hand, "closure" is universal - it remains, as far as I'm aware, untranslated in other languages. Therefore, "closure" as a suffix (or prefix) could be better in scripts that are likely to be used/modded on a world-wide basis.

Is using too many static variables in Objective-C a bad practice?

Will usage of static variables expose them to a danger of being modifiable from anywhere ?(In context of Objective-C). If yes, can someone suggest best alternatives for using shared variables across all classes ?
Is using too many static variables in Objective-C a bad practice?
Yes. Of course, "too many" has not been quantified and is subjective. Really, global/static variables are very rarely a good thing -- very convenient to introduce and very difficult to debug and eliminate. Also rare is the case that they are good design. I've found life far easier without them.
Will usage of static variables expose them to a danger of being modifiable from anywhere? (In context of Objective-C).
It depends on where they are declared and how they are used. If you were to pass a reference to another part of the program, then they would be modifiable from 'anywhere'.
Examples:
If you place them so that only one file can "see" the variable (e.g. in a .m file following all includes), then only the succeeding implementation may use it (unless you pass a reference to the outside world).
If you declare the variable inside a function, then it is shared among each translation and copied for each translation in C/ObjC (but the rules are very different in C++/ObjC++).
If yes, can someone suggest best alternatives for using shared variables across all classes?
Just avoid using globals altogether. Create one or more type/object to hold this data, then pass an instance of it to your implementations.
Singletons are the middle ground, in that you have some type of global variable/object based abstraction. Singletons are still so much hassle -- they are categorized as global variables and banned in my codebase.
Static variables are local to the translation unit, so the variables are definitely not modifiable from anywhere. Globals, which are closely related to statics in that they are allocated in the same memory area, are modifiable from anywhere, and that's their main danger.
When you need a group of variables to be accessible from anywhere in your project, the common approach is implementing a singleton that holds related data, and contains methods for processing that data. In MVC apps implemented in Objective C the model is often accessed through a singleton model object.
My scenario involves a number of static variables declared in the .h file & they are assigned values in specific methods declared in those .h files.
If you declare statics in the header, they become "disconnected" from each other: each translation unit (i.e. each .m file) gets its own set of statics from the header. This is usually not what you want.
If you make these variables global, you end up with a plain C, not an Objective C, solution. You should put these variables in a class as properties, and move function implementations with them into the methods of your class. Then make the class a singleton as described in the answer linked above to get a solution that is easier to understand than the corresponding solution based on globals.

Usage of inline closures / function delegates in Actionscript

Why are inline closures so rarely used in Actionscript? They are very powerful and I think quite readable. I hardly ever see anyone using them so maybe I'm just looking at the wrong code. Google uses them in their Google Maps API for Flash samples, but I think thats the only place I've seen them.
I favor them because you have access to local variables in the scope that defines them and you keep the logic in one method and dont end up with lots of functions for which you have to come up with a name.
Are there any catches of using them? Do they work pretty much the same way as in C#.
I actually only just discovered that AS3 supports them, and I'm quite annoyed becasue I had thought I read that they were deprecated in AS#. So I'm back to using them!
private function showPanel(index:int):void {
_timer = new Timer(1000, 1);
_timer.addEventListener(TimerEvent.TIMER, function(event:Event):void
{
// show the next panel
showPanel(index++);
});
The biggest gotcha to watch out for is that often 'this' is not defined in the inline closure. Sometimes you can set a 'this', but it's not always the right 'this' that you would have available to set, depending on how you're using them.
But I'd say most of the Flex code I've worked on has had inline closures rampantly throughout the code--since callbacks are the only way to get work done, and often you don't need the bring out a whole separate function.
Sometimes when the function nested is getting to be too much, I'll break it out slightly with Function variables in the function; this helps me organize a bit by giving labels to the functions but keeping some of the characteristics of inline closures (access to the local variables, for example).
Hope this helps.
One additional problem is that garbage collection is broken when it comes to closures (at least in Flash 9). The first instance of a given closure (from a lexical standpoint) will never be garbage collected - along with anything else referenced by the closure in the scope chain.
I found what originally made me NOT want to do this, but I had forgotten the details:
http://livedocs.adobe.com/flex/3/html/16_Event_handling_6.html#119539
(This is what Mitch mentioned - as far as the 'this' keyword being out of scope)
So thats Adobe's answer, however I am much more likely to need to refer to local variables than 'this'.
How do others interpret Adobe's recommendation ?

Resources