This paper is mainly on the industry mainstream programming paradigm (programming thought) to do a summary of exposition, clarify the differences between each programming paradigm, advantages and disadvantages, hoping to provide some help for you to understand the programming paradigm system.

Programming paradigm is not strong

Three dominant programming paradigms

Imperative programming

Here’s an example:

On the weekend, I wanted a grilled chicken wing for lunch, and THEN I:

Go to the market to buy some chicken wings; Wash and marinate chicken wings; Put into the oven, set the baking temperature and time, start baking; Remove wings from oven and transfer to plate.

Start eating chicken wings…

In the example, IT is obvious that I want to eat chicken wings. In order to achieve this goal, I take specific steps to do the corresponding things, and finally achieve the goal of eating chicken wings. This is imperative programming.

The main idea of imperative programming is to focus on the steps the computer performs, telling the computer step by step what to do first and what to do next. Imperative programming is the most common form of programming, which can be followed by all major programming languages such as C, C++, JAVA, etc.

For example, to find all elements greater than 5 in a given collection of numbers, the JAVA language can write:

List<Integer> results = new ArrayList<>(); for (int num : collection) { if (num > 5) { results.add(num); }}Copy the code

This is a typical example of imperative programming written as follows:

  1. Define a result list to store the results of the execution.
  2. Iterate over the elements of the original list one by one;
  3. For each element, check if it is greater than 5 and place it in the result list.
  4. Continue the for loop until the loop completes.

This code clearly tells the computer the specific execution process of each step, and then the computer executes each command according to the process of code execution.

As can be seen from the above example:

Imperative programming modifies modifiable variables through assignment (consisting of expressions and variables) and control structures (e.g., conditional branching, looping statements, etc.).

In plain English, it is a sequence of instructions in a computer, executed one by one in a written order or by jump logic (for/while/goto, etc.). The efficiency of program execution depends on the number of instruction sequences, the space occupied by variables and other factors. Therefore, there is the concept of time complexity and space complexity to measure the merits of an algorithm.

Declarative programming

Continuing with the chicken wing example.

On the weekend, I want a grilled chicken wing tonight… Me: Mom, I want to have the grilled chicken wings… (After a while) Mom: Here come the grilled chicken wings… I started eating chicken wings…

In this example, I wanted to have roast chicken wings, but I didn’t do it step by step as before, but passed my appeal to my mother, who then prepared the chicken wings and realized my appeal. In my case, all I need to do is declare that I want to eat the chicken wing, and I don’t care how the chicken wing is made. This is declarative programming.

The main idea of declarative programming is to tell the computer what to do without specifying how to do it. Typical declarative programming languages, such as SQL, regular expressions, etc.

SELECT * FROM collection WHERE num > 5
Copy the code

Here’s another example of declarative programming in JAVA:

List<Integer> results = getAllGreaterThan5Numbers(collection);
Copy the code

This is a typical example of declarative programming. For the current caller, just tell the computer that I now need to get all the numbers greater than 5 from the collection, As for getAllGreaterThan5Numbers () concrete is step by step, how to implement this method will be greater than 5 digital filtering, the caller no care.

Functional programming

Just to be clear, this function is not that function.

To programmers, functions generally refer to functions/methods in various programming languages, but functions in functional programming refer to mathematical functions, that is, mappings.

Here’s an example:

y = f(x)
f(x) = x + 1
Copy the code

In this mathematical formula, f of x is a function, but the name of the table is a relationship between x and y, so x plus 1 is y. In this case:

If x=1, then y=f(x) evaluates to 2. If x=2, y=f(x) evaluates to 3. If x=3, y=f(x) evaluates to 4. .Copy the code

So, the nature of a function is obvious: it takes one or more inputs, produces one or more corresponding results, and the relationship between inputs and outputs is clear and fixed, not affected by previous inputs. That is:

When a function gets the same result (no side effects, referential transparency) no matter how many times it is called, no matter who calls it, no matter what is passed in, as long as it keeps the same input.

Now that you know what functional is, let’s go back to functional programming. The core idea is the same as declarative programming: focus on what you do, not how you do it. So in this sense, functional programming is part of declarative programming.

List<Integer> results = 
    collection.stream()
              .filter(n -> n > 5)
              .collect(Collectors.toList());
Copy the code

Going back to the previous description of functions, in mathematics, the input variable x to f(x) actually represents a specific number that needs to be plugged into the function formula. Similarly, ina functional programming scenario, variables passed into a function are also non-assignable (of type final), i.e., the value of a variable is immutable. Specifically:

  • The value of a variable passed in by a function cannot be changed once bound.
  • Instead of saying that the variable passed in is a value, sayThe variable passed in is an expression(Lazy evaluation).

Of course, the concept of functional programming is a very large theoretical framework, and in addition to the above mentioned features, there are other features (such as Currization) that I will not elaborate on here.

smackdown

Imperative programming VS declarative programming

As usual, here’s an example from life:

One afternoon, at home. Wife: “husband, I want to eat 1000 layer cake”. . (After some time)… Husband: “wife, give you thousand layer cake”

The above is a classic example of declarative programming, saying what you want and not how you do it. The wife only told her husband to eat melaleuca cake, and then the husband is responsible for the melaleuca cake to the wife, as for the husband is how to get this melaleuca cake, in the end is to go out to buy, or the takeaway point, or their own hands do, the wife is not concerned about.

Evolve the above example:

One afternoon, at home. Wife: “husband, I want to eat a thousand layer cake, you go to the phone to download a XX food APP, and then search the need for what materials, and then walk to the village diagonally opposite the vegetable market inside to buy a chicken leg, and then go to the opposite supermarket inside to buy the rest of the accessories, finally come back to do thousand layer cake for me to eat”. . (The husband followed his wife’s instructions, first downloaded the APP, then searched for the needed materials, then went to the market to buy vegetables, to buy accessories in the supermarket, and began to make cakes at home… After a period of time…) . Husband: “wife, give you thousand layer cake”

In this example, the wife directive tells you exactly what to do step by step, which is the beginning of imperative programming. Obviously, compared with the previous declarative programming, the wife in this example obviously needs to worry about everything, trouble a lot, but in the previous example, can be a hand off the owner, after issuing a demand, waiting to eat

Expand on the above example:

One afternoon, at home. Step1 wife: “husband, I want to eat a thousand layer cake”. Step2 husband begins to search recipe tutorial, prepare food material, follow recipe step by step do cake (tired full head sweat)… Step3 husband: “wife, give you thousand layer cake”

In this case, for the wife, as I mentioned above, it’s declarative programming. For the husband in Step2, it is completely imperative programming, he needs to know exactly what needs to be done in each step, and finally make the cake.

Can see from the above three examples, if you want to achieve a pursuit, is certainly need some demands, some specific worry to achieve, and the wife whether when cutting the shopkeeper, depends on whether the husband enough universal (of course, the program apes husband affirmation is universal, or else how can have a wife… Ha ha).

In the development scenario, the wife in the example is the business module, and the husband is the various encapsulated tool classes, open source library functions, etc. If there is a strong enough library function support to implement the complex logic at the bottom, then the business logic layer is responsible for the command.

Let’s go back to the code level and take a look at the complete code for the example mentioned earlier in declarative programming:

// Declarative programming that tells you what to do without caring how to do itList<Integer> results = getAllGreaterThan5Numbers(collection); .// Imperative programming, telling the computer the logic of each step of operation
private List<Integer> getAllGreaterThan5Numbers(List<Integer> collection) {
    List<Integer> results = new ArrayList<>();
    for (int num : collection) {
        if (num > 5) { results.add(num); }}return results;
}
Copy the code

Declarative programming is the simplest approach, but declarative programming usually relies on imperative programming. Declarative programming can be achieved, because related library function, or a custom tool function (such as in the example here getAllGreaterThan5Numbers () method) will be implemented step by step, the underlying concrete to encapsulate the logic, and method of these tools, Ultimately, it needs to be done in the form of imperative programming (isn’t that like the “husband” and “wife” examples above?). .

Of course, there is no better style of imperative programming than declarative programming. Declarative programming is better for programmers because of human inertia. Also, from a code debugging perspective, declarative programming is not easy to debug, or even impossible to debug (for example, when calling apis from other libraries or dependent packages and no source code is available). In addition, for large project systems, imperative programming and declarative programming are certainly interdependent.

So, this gives us a very important lesson:

  • Project, for the public tool method packaging, must ensure absolute accuracy, absolutely reliable!
  • When selecting a technology, a tripartite or open source framework or tool library should be selected as iteratively mature and stable as possible.
  • When you stand on the shoulders of giants and have the tools at your disposal, avoid reinventing the wheel behind closed doors.

Imperative programming VS functional programming

With the rapid development of hardware, almost all cpus support multi-core operation. However, due to the efficiency bottleneck of CPU single-core execution, the concept of multi-core programming has been paid more and more attention.

For imperative programming, its execution time can only occupy the single-core CPU processing (note: with the traditional sense of the multi-thread concurrent is not a concept), if you need to implement a multi-core programming, may need to be done to the code changes, and then based on multi-thread concurrent programming and other means to achieve, complexity and difficulty will be much higher.

Find all elements greater than 5 in a given list of numbers. We have already seen the code for imperative programming:

List<Integer> results = new ArrayList<>();
for (int num : collection) {
    if (num > 5) { results.add(num); }}Copy the code

Obviously, we all know that when this code is executed, it must be executed from top to bottom in a single-core single thread. Given that the list of collection numbers is very large and the logic in the for loop is time-consuming, this code will definitely take a long time to execute. How should we optimize it? Easy to imagine, multithreading!

Continuing with the above example, we can modify it to multithreaded parallel processing logic like this (there are several ways, but here is just a simple implementation ~) :

  1. Create a thread pool that maintains several threads of execution, say 10.
  2. The run() method encapsulates specific logic.
  3. Divide the collection contents 10 equally among the 10 threads in the thread pool for processing.
  4. Create a thread-safe result set container for storing filtered results processed by each thread.
  5. Wait for all threads to finish processing to get the final result set.

Specific code is not posted, all in all, you can see, in imperative programming, to achieve a multi-core programming, need extra many complex processing logic to implement, but also focus on the concept of all kinds of semaphore, lock is a little careless, it’s easy to have a serious problem, which is also an imperative programming line about concurrent programming content enough to hold up a thick textbook.

Looking at functional programming, functional programming seems to have been built for multi-core programming, breaking the shackles of single-core programming due to the existence of a loop body. The appearance of functional programming opens up a new world for various library functions, which can provide a variety of more convenient API interfaces. For example, with a Stream in JAVA, parallelism can be done in a single line of code:

List<Integer> results = 
    collection.parallelStream()
        .filter(n -> n > 5)
        .collect(Collectors.toList());
Copy the code

The last

In a large system, the various programming paradigms are generally integrated and complementary. It can only be said that the right thing should be done in the right place and in the right way. The specific degree should be controlled according to the actual situation. Of course, as a new favorite of various programming languages in recent years, functional programming is still worth learning, which can effectively simplify our code logic, enhance readability, improve parallel processing efficiency and so on.

Refer to the content

Some of the opinions and contents in this article are from the Internet.

  • Functional programming versus imperative programming


Welcome to pay attention to my public account “Architecture Record”, the first time to push original technical articles, can also interact with the discussion of communication technology.