Imperative programming vs declarative programming

Source: Internet
Author: User

English Original: Imperative vs declarative
To unify the concept first, we have two ways of programming: imperative and declarative.
We can define the difference between them as follows:

    • Imperative programming: Command "Machine" How to do things, so whatever you want, it will follow your command.
    • Declarative programming: Tell the Machine what you want (what), and let the machine figure out how to do it.

Code examples for declarative programming and imperative programming for example, let's say we want to double the values in an array.

1. We implement it in an imperative programming style, like this:

var  numbers = [1 , 2 , 3 , 4 , 5 ]var  doubled = []< Span class= "Hljs-keyword" >for  (var  i = 0  ; i < numbers.length; i++) {var  newnumber = numbers[i] * 2  Doubled.push (Newnumber)} console . Log (doubled) // =>  [2 , 4 , 6 , Span class= "Hljs-number" >8 , 10 ]  

We iterate through the entire array, take each element, multiply it by two, and then put the doubled value into the new array, manipulating the double array every time until all the elements have been computed.

2. Instead of using declarative programming methods, we can use the Array.map function, like this:

var numbers = [1,2,3,4,5]var doubled = numbers.map (function (n) {  return2//=> [2,4,6,8,10]

Map creates a new array with the current array, and each element in the new array is processed by the function (n) {return n*2}) passed into the map.
  

In some languages with functional programming features, there are other commonly used declarative function methods for the operation of list data types. For example, to ask for all the values in a list and command programming to do so:

varnumbers = [1,2,3,4,5]varTotal =0  for(vari =0; i < numbers.length; i++) {Total + = Numbers[i]}console.log (total)//=>//And in declarative programming, we use the Reduce function:varnumbers = [1,2,3,4,5]varTotal = Numbers.reduce ( function (SUM, N) {  returnSum + n}); Console.log (total)//=>

The reduce function uses an incoming function to operate a list into a value. It takes this function as a parameter, and each element in the array is processed by it. Each invocation, the first argument (this is sum) is the result of the function's handling of the previous value, and the second parameter (n) is the current element. This way down, each new element of this process is summed into sum, and finally we get the entire array of sums.
Similarly, the reduce function induces the implementation of how we traverse the array and state management sections, providing us with a common way to combine a list into a single value. All we need to do is to indicate what we want.
  
 3. Declarative programming is that weird?
  
If you have not heard of the map and the reduce function before, your first feeling, I believe, will be like this. As programmers, we are very accustomed to pointing out how things should work. "Go through the list", "If this happens then," and "assign this new value to this variable". When we already know how to tell a machine how to do things, why do we need to learn this seemingly weird inductive pull-out function tool?
In many cases, imperative programming is useful. When we write business logic, we usually have to write imperative code, there is no possibility in our special business There is also a can be summed out the implementation of the extraction.

 Declarative programming Language: SQL
 
Maybe you don't understand, but there's a place where you might have used declarative programming, which is SQL.
You can think of SQL as a declarative query language for processing data. Write an application entirely in SQL? That's impossible. But it's incredibly powerful if you're dealing with an interconnected set of data.
Query statements such as the following:

select * from Dogsinner JOIN ownerswhere dogs.owner_id = owners.id If we implement this logic in an imperative way://dogs = [{name:  ' Fido ' , owner_id: 1 }, {},  ... ] Owners = [{ID: 1 , Name: }, {

I did not say that SQL is a very easy to understand language, and can not say a glance to see them, but basically still very neat. The
SQL code is not only very short, it is not only easy to read, it also has a greater advantage. Because we're inductive, we can focus on what, and let the database help us optimize how.
Our imperative programming code will run very slowly because we need to traverse the owner of every dog in the list.
and in the SQL example we can get the database to handle how, to find the data we want for us. If you need to use an index (assuming we've built an index), the database knows how to use the index, so there's a big improvement in performance. If it has executed the same query before this time, it may be found immediately in the cache. By letting go of how, let the machine to do these difficult things, we do not need to master the principle of the database can easily complete the task.

Declarative Programming: D3.js
Another truly powerful place to demonstrate declarative programming is user interface, graphics, and animation programming.
It is difficult to develop a user interface. Because of the user interaction, we want to create beautiful dynamic user interaction, usually we use a lot of state declarations and many of the same function of the code, which can actually be summed up. The example of a very good declaration in
D3.js is a toolkit that helps us to develop interactive and animated data visualization models using JavaScript and SVG.
First (or 5th, even 10th = times) You may have a big head when you develop the D3 program. Like SQL, D3 is a powerful common tool for visualizing data operations, and it gives you all the ways you need to say what you want.
Here is an example (I suggest you take a look at this demo). This is a D3 visual implementation that draws a circle for each object in the data array. To demonstrate this process, we add a circle per second. The most interesting piece of code in the
is:

//var data = [{x:5, y:10}, {x:20, y:5}]  var  circles = svg.selectall ( ' Circle ' ). Data (data) Circles.enter (). Append ( ' Circle ' ). attr ( ' CX ' , Span class= "hljs-function" >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 is doing (you need some time to understand it), but the key point is:
First we collect all the circles in SVG and then bind the data array to the object.
D3 has a relational table that binds the point data to each circle. Initially we had only two points, no circles, and we used the. Enter () method to get the data points. Here, our intention is to draw a circle, the center is x and y, the initial value is 0, half a second after the transformation into a radius of 5.
Why do I say it's funny?
Look at the code from the beginning and think about it, we're declaring what we want to look like, or how we're going to figure it out. You'll find there's no code for how. We're just describing what we want at a fairly high level:
I'm going to draw a circle, the center of the data, when the new circle is added, the radius is increased by the animation.
This is amazing, we didn't write any loops, there's no state management. Drawing operations are often difficult to write, cumbersome, and annoying, but here, D3 inductive extracts some of the common operations that let us focus on describing what we want.
Now look again, D3.js is easy to understand? No, it definitely requires you to spend some time studying. The process of learning basically requires you to give up the habit of pointing out how to do things, and learn how to describe what I want.
Initially, this may be difficult, but after some time of learning, something magical happens-you become very, very effective. By inductive extraction, how,d3.js allows you to truly focus on what you want to see, to solve problems at a higher level, and to liberate your creative power.
  
Summary of declarative programming
  
Declarative programming lets us describe what we want, let the underlying software/computer/And so on to solve how to implement them.
In many cases, as we've seen, declarative programming can bring real improvements to our programming, and by standing at a higher level, we can focus more on what, and that's exactly what we're developing software for.
The problem is that programmers get used to describing how, which makes us feel good and comfortable--powerful--to control the development of things, and not to let go of any process that we cannot see that we cannot understand.
Sometimes it's okay to keep a close eye on how. If I need to optimize my code for higher performance, I need a deeper description of what to do to guide how. Sometimes there is no generic implementation for a business logic that can be summed up, and we can only write imperative programming code.
But most of the time, we can, and should seek to write a declarative way of writing code, if we do not find a ready-made inductive extract good implementation, we should create it ourselves. At first it would be hard, sure, but as we use SQL and d3.js, we'll get huge rewards for the long haul!
  
Transferred from: http://kb.cnblogs.com/page/181030/

Imperative programming vs declarative programming

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.