What is a closure?

Source: Internet
Author: User

First of all, I think it is not necessary to understand or learn a concept if it is not understood or affected. Closure is such a concept that you can use well without understanding it. I wrote as3 in the past two years.ProgramI am dealing with it every day. I even have an extreme example of one function and more than 20 functions in one method, but I have never studied how it is implemented, like water and air, we don't need to know that water is H2O, and Air is a mixture of oxygen, nitrogen, and carbon dioxide.

Secondly, I think the online explanation of the closure concept is too narrow, and it seems like I ++ and I are back. If you have to understand this concept and understand it like that, the gains are too small to be worth it.

Wikipedia's interpretation of closures is classic:

In computer science, closure is short for lexical closure, a function that references free variables. This referenced free variable will exist with this function, even if it has left the environment where it was created. Therefore, there is another saying that a closure is an entity composed of a function and its reference environment.

Peter J. landin defined the term closure as an entity that contains environmental and control components in 1964.

Below are the closure concepts I understand.

First look at the closure in mathematics.

() Is an interval. However, when analyzing and calculating this interval, we often use values 1 and 5 that do not belong to this interval. [] is).

In our daily lives, we need to go to department a and department a to create a chapter for department B. Department B said, you must first build a chapter for Department C, department C said that this is not our function scope ...... Play the ball. This is a non-closure. Closure is responsible for the end. If you find Department A, the person who receives Department A is responsible for the end, and he/she coordinates department B and Department C.

In the project, closure is the project manager responsible for scheduling the resources required by the project. If there is anything for the boss and the customer, you can directly find the project manager without looking for other people.

In programming languages, closure is a syntactic sugar. It automatically packs all the resources involved in our purpose and our purpose in a natural form, use it in a natural way that is as easy as possible to avoid misunderstanding. As for its specific implementation, I personally agree that, without affecting the use of the service, I will not provide a thorough explanation. In many casesCodeTo access external local variables. If this syntax sugar is not provided, you need to write a lot of code. With the closure syntax sugar, you don't need to write so much code, naturally, it is used.

In this way, the closure can be upgraded from a syntax mechanism to a design principle:

Closure is a design concept from the user's point of view. Based on context analysis, it does everything that involves complex things and external environment interaction, it leaves users with a natural interface.

Under this principle, in Functional Languages, the so-called closure is just a "closure", and there are a large number of other types of "closure" waiting for discovery and implementation.

Below are some examples of Closure design principles.

Example:

The Data Binding syntax in Flex is a "closure ". X = "{B. num + C. num} ", for this syntax, the compiler automatically goes to the context to find the variables called B and C, and then finds their internal num variables. If they are all Bindable, the BIND chain is automatically added to them. The value of X is updated when B, C, num, and other changes exist.

Counterexample:

The design in winform violates the closure principle. When the value of some controls is updated not in the UI thread, an exception is thrown. It can only be called by invoke, but the invoke interface is very difficult to use. I believe many people are very disgusted with this.

Closures are not necessarily syntactic sugar. When we cannot directly extend the compiler, we cannot add syntactic sugar to implement the closure mechanism. At this time, we need to use the existing language mechanism to implement it.

Next, we will transform the winform invoke method to meet the closure principle. The following code is used:

Public class controlfunccontext
{
Public Control {Get; private set ;}
Public Delegate delegate {Get; private set ;}

Public controlfunccontext (control CTL, delegate D)
{
This. control = CTL;
This. Delegate = D;
}

Public void invoke0 ()
{
If (control. ishandlecreated = true)
{
Try
{
Delegate. dynamicinvoke ();
}
Catch (objectdisposedexception ex)
{
}
}
}

Public void invoke1 <t> (t obj)
{
If (control. ishandlecreated = true)
{
Try
{
Delegate. dynamicinvoke (OBJ );
}
Catch (objectdisposedexception ex)
{
}
}
}

Public void invoke2 <T0, T1> (T0 obj0, T1 obj1)
{
If (control. ishandlecreated = true)
{
Try
{
Delegate. dynamicinvoke (obj0, obj1 );
}
Catch (objectdisposedexception ex)
{
}
}
}
}

Public static class formclasshelper
{

Public static void invokeaction (this control CTL, action Action)
{< br> If (CTL. ishandlecreated = true)
{< br> controlfunccontext fc = new controlfunccontext (CTL, action);
CTL. invoke (new action (FC. invoke0);
}< BR >}

Public static void invokeaction (this control CTL, Action action, t OBJ)
{< br> If (CTL. ishandlecreated = true)
{< br> controlfunccontext fc = new controlfunccontext (CTL, action);
CTL. invoke (new action (FC. invoke1 ), OBJ);
}< BR >}

Public static void invokeaction <T0, T1> (this control CTL, Action <T0, T1> action, t0 obj0, T1 obj1)
{
If (CTL. ishandlecreated = true)
{
Controlfunccontext fc = new controlfunccontext (CTL, action );
CTL. Invoke (new action <T0, T1> (FC. invoke2 <T0, T1>), obj0, obj1 );
}
}
}

It's easy to use. You just need to call the extension method invokeaction directly. You don't have to consider cross-thread or non-Cross-thread "environment factors". Cross-thread calls are already done in a way that you don't have to know, encapsulate it.

For another example, writing a program often requires the function of opening an image file and processing it. It is difficult to write normally. For example, if the filter format is easy to forget, we will closure it and let users know whether it should be used, it should not be encapsulated for users to press the keyboard:

Public static void openfile (this form element, Action <string> callbackonfilepath, string filter = "all files | *.*")

{

String filepath;

Openfiledialog DLG = new openfiledialog ();

DLG. Filter = filter;

DLG. fileok + = (Object sender, canceleventargs e) =>

{

Filepath = DLG. filename;

If (callbackonfilepath! = NULL)

Callbackonfilepath (filepath );

};

DLG. showdialog ();

}

Public static void openimagefile (this form element, Action <string> callbackonfilepath, string filter = "Image File | *. BMP; *. jpg; *. gif; *. PNG ")

{

Openfile (element, callbackonfilepath, filter );

}

Another example is in as3. In Flex, the control has a calllater method that is called at the next frame. This method is very useful. In many cases, this method is also required for non-Flex projects. Below, we simulate:

Package Orc. utils
{
Import flash. display. stage;
Import flash. Events. event;

Public class calllaterhelper
{
Public Function calllaterhelper (stage: stage, callback: function)
{
This. Callback = callback;
This. Stage = stage;

Stage. addeventlistener (event. enter_frame, onstageenterframe );
}
Private var stage: stage;
Private var callback: function;
Private function onstageenterframe (Event: Event): void
{
Stage. removeeventlistener (event. enter_frame, onstageenterframe );
If (callback! = NULL)
{
Callback ();
}
}
}
}

Then, in the basic control, the calllater method is provided:

Public Function calllater (callback: function): void
{
New calllaterhelper (this. Stage, callback );
}

Summary:

(1) closure is a design principle. It analyzes the context to simplify user calls, so that users can achieve their purpose without knowing it;

(2) Mainstream online analysis of closuresArticleIn fact, it is in reverse direction with the closure principle. If you need to know the details of the closure to make good use of it, this closure is designed to fail;

(3) Try to learn as little as possible.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.