We have two programming methods: imperative and declarative. This article uses the code display method to define the differences between the two methods, and how to select and use the two programming methods in daily practice. We can define the differences between them as follows: • imperative programming: the command "machine" such ...,. First, let's unify the concept. We have two programming methods: imperative and declarative.
We can define the differences between them as follows:
• Imperative programming: The command "machine" how to do things, so no matter what you want (what), it will follow your command.
• Declarative Programming: Tell the "machine" what you want and let the machine figure out how to do it ).
Code example of declarative and imperative Programming
Let's take a simple example. Suppose we want to double the value in an array.
We use the imperative programming style as follows:
var numbers = [1,2,3,4,5]var doubled = []for(var i = 0; i < numbers.length; i++) { var newNumber = numbers[i] * 2 doubled.push (newNumber)}console.log (doubled) //=> [2,4,6,8,10]
We directly traverse the entire array, retrieve each element, multiply it by two, and then put the doubled value into the new array. Each time we operate the double array until all elements are computed.
With Declarative Programming, we can use the Array. map function, as shown below:
var numbers = [1,2,3,4,5]var doubled = numbers.map (function (n) { return n * 2})console.log (doubled) //=> [2,4,6,8,10]
Map creates a new array using the current array. Each element in the new array is a function passed in to map (function (n) {return n * 2 }).
What the map function does is to extract the process of directly traversing the entire array, so that we can focus on what we want ). Note that we pass in a map is a pure function; it does not have any side effects (does not change the external State), it only receives a number, returns the value multiplied by two.
In some languages with functional programming features, there are other commonly used declarative Function Methods for list data type operations. For example, to find the sum of all values in a list, the imperative programming will do this:
var numbers = [1,2,3,4,5]var total = 0 for(var i = 0; i < numbers.length; i++) { total += numbers[i]}console.log (total) //=> 15
In Declarative Programming, we use the reduce function:
var numbers = [1,2,3,4,5]var total = numbers.reduce (function (sum, n) { return sum + n});console.log (total) //=> 15
The reduce function uses the input function to calculate a list into a value. It takes this function as a parameter, and each element in the array must be processed by it. Each call, the first parameter (sum here) is the result returned when this function processes the previous value, and the second parameter (n) is the current element. In this way, each new element of the processing is aggregated into sum, and we finally get the sum of the entire array.
Similarly, the reduce function extracts the implementation of how we traverse the array and State management, and provides us with a general method to combine a list into a value. What we need to do is to specify what we want?
Is Declarative Programming strange?
If you have never heard of map and reduce functions before, I believe this will happen. As programmers, we are very accustomed to pointing out how things should run. "Traverse this list", "if in this case then does that", "assign this new value to this variable ". When we already know how to tell machines how to do things, why do we need to learn such weird function tools?
In many cases, imperative programming is useful. When we write business logic, we usually have to write imperative Code. There is no possibility of an implementation that can be summarized and extracted in our special business.
However, if we take the time to learn (or discover) declarative components that can be extracted, they can bring great convenience to our programming. First, I can write less code, which is a shortcut to success. In addition, they allow us to think at a higher level, think about what we want on the cloud, rather than thinking about how to do things.
Declarative Programming Language: SQL
Maybe you still cannot understand, but one thing you may have used Declarative Programming, that is, SQL.
You can use SQL as a declarative query language for data processing. Write an application completely using SQL? This is impossible. However, if it is to process correlated datasets, it will be incredibly powerful.
The following query statement is used:
SELECT * from dogsINNER JOIN ownersWHERE dogs.owner_id = owners.id
If we use imperative Programming to Implement this logic:
//dogs = [{name: 'Fido', owner_id: 1}, {...}, ... ]//owners = [{id: 1, name: 'Bob'}, {...}, ...] var dogsWithOwners = []var dog, ownerfor(var di=0; di < dogs.length; di++) { dog = dogs[di] for(var oi=0; oi < owners.length; oi++) { owner = owners[oi] if (owner && dog.owner_id == owner.id) { dogsWithOwners.push ({ dog: dog, owner: owner }) } }}}
I did not say that SQL is a language that is easy to understand, and I can understand them at a glance, but it is basically neat.
SQL code is not only short, but not easy to understand. It also has a greater advantage. Because we extracted how, we can focus on what and let the Database Help us optimize how.
Our imperative programming code runs very slowly, because we need to traverse the Masters of every dog in all lists.
In the SQL example, we can let the database handle how and find the data we want for us. If you need to use an index (assuming we have created an index), the database knows how to use the index, which greatly improves the performance. If it executes the same query not long ago, it may be found immediately from the cache. By letting the machine do these difficult tasks, we can easily complete the task without having to master the database principles.
Declarative Programming: d3.js
Another truly powerful aspect of sound-aware programming is user interface, graphics, and animation programming.
It is difficult to develop the user interface. Because of user interaction, we hope to create a beautiful dynamic user interaction mode. We usually use a lot of State declarations and a lot of code with the same function, these codes can be summarized and extracted.
In d3.js, an example that is summarized during a very good declaration is a toolkit that helps us develop interactive and animated data visualization models using JavaScript and SVG.
The first time (or 5th times, or even 10th = times) you develop the d3 program may be too large. Similar to SQL, d3 is a powerful and universal tool for visualized data operations. It provides all your how methods so that you only need to say what you want.
The following is an example (I suggest you take a look at this demonstration ). This is a d3 visualization implementation, which draws a circle for each object in the data array. To demonstrate this process, we add a circle every second.
The most interesting piece of code is:
//var data = [{x: 5, y: 10}, {x: 20, y: 5}]var circles = svg.selectAll('circle') .data(data)circles.enter().append('circle') .attr('cx', function(d) { return d.x }) .attr('cy', function(d) { return d.y }) .attr('r', 0) .transition().duration(500) .attr('r', 5)
There is no need to fully understand what this code has done (you need to understand it for a while), but the key points are:
First, we collect all the circles in svg, and then bind the data array data to the object.
D3 binds each circle to those vertices and has a relational table. At first we had only two vertices without circles. We used the. enter () method to obtain the data points. Here, our intention is to draw a circle with the center x and y, the initial value is 0, and the radius is 5 after half a second.
Why do I say this is interesting?
Read the code from the beginning and think about whether we are declaring what the pattern we want is, or how to plot it. You will find that there is no code about how. We only describe what we want at a very high level:
I want to draw a circle. the center of the circle is in the data. When a new circle is added, an animation is used to represent the increase of the radius.
This is amazing. We didn't write any loops, and there was no State management here. Drawing operations are usually hard to write, difficult, and annoying. But here, d3 extracts some common operations, allowing us to focus on describing what we want.
Now let's look at it again. Is d3.js easy to understand? No, it definitely takes you some time to learn. The learning process basically requires you to give up the habit of specifying how to do things and learn how to describe what I want.
It may be difficult at first, but after some time of study, some magical things happen-you become very efficient. By summarizing how, d3.js enables you to focus on what you want to see, solve problems at a higher level, and free up your creativity.
Summary of Declarative Programming
Declarative Programming allows us to describe what we want and let the underlying software/computer/etc solve how to implement them.
In many cases, just as we can see, Declarative Programming can truly improve our programming. By writing code at a higher level, we can focus more on what, this is the real goal of software development.
The problem is that programmers are used to describing how, which makes us feel very comfortable-powerful-being able to control the occurrence and development of things without letting us go through any process that we cannot see and understand.
Sometimes it's okay to keep an eye on how. If I want to optimize code with higher performance, I need to describe what to guide how. Sometimes there is no general implementation that can be summarized and extracted for a business logic. We can only write imperative programming code.
But most of the time, we can and should look for declarative code writing methods. If there is no ready-made implementation of inductive extraction, we should create it ourselves. At first, this would be difficult and certain, but like using SQL and D3.js, we will get a huge return for a long time!
The above are the declarative and imperative content of the two commonly used programming methods. For more information, see the PHP Chinese website (www.php1.cn )!