Paradigm-the idea behind the programming language

Paradigm-the idea behind the programming language

Author: IMWeb Zhoulu Jun microblogging ORIGINAL: IMWeb community without consent, is prohibited reprint

Programming paradigm

After Thomas Kuhl proposed the paradigm theory of "scientific revolution", Robert Floyd used the term programming paradigm in his 1979 Turing Award presentation. Programming paradigm generally includes three aspects, take OOP as an example:

1. The logical system of the discipline-rule paradigm: mechanisms such as class/object, inheritance, dynamic binding, method rewriting, object replacement, etc.

2. Psychological cognitive factors-psychological paradigm: According to Alan Kay, the father of object-oriented programming, "computation is simulation". The OO paradigm attaches great importance to the value of metaphor, and simulates nature in a natural way through personification.

3. Natural view/world view-conceptual paradigm: Emphasizes the organization technology of the program, treats the program as a combination of loosely coupled objects/classes, organizes the classes into a hierarchical structure through the inheritance mechanism, and treats the operation of the program as one of the objects that serve each other Dialogue between.

To put it simply, the programming paradigm is the programmer's view of the program, which represents the programmer's view of how the program should be constructed and executed.

Common programming paradigms are: imperative, procedural, declarative, object-oriented, functional, generic programming, etc.

Imperative Imperative||Procedural

* Von Neumann machine language, assembly language BASIC COBOL C Ada FORTRAN Fortran,

*Scripted Perl Python PHP, which "sticks together" independent programs developed in other languages as components

*Object-oriented Smalltalk C++ Java, based on the interaction of independent objects. Each object has its own internal state and executable subroutines that manage its own state

Declarative Declarative||Declarative

*Functional Lisp ML Haskell, the program is seen as a function from input to output

*Data flow ld Val, the language regards calculation as a flow of information flowing between some basic functional nodes. The node is triggered by the arrival of the input word and can be operated concurrently

*Logical Prolog, try to find out the value that satisfies some specific relationship according to a set of logic rules

* XSLT xml html based on template ,

What needs to be reminded is that the programming paradigm is a classification of programming languages, and it is not specific to a certain programming language . As far as programming languages are concerned, one language can apply multiple programming paradigms .

Some programming languages are specifically designed for a specific paradigm. For example, C language is a procedural programming language; Smalltalk and Java are purer object-oriented programming languages; Haskell is a purely functional programming language. In addition, some programming languages do not have a one-to-one correspondence with programming paradigms. For example, Python, Scala, and Groovy all support object-oriented and functional programming to a certain extent. C++ is a successful example of a multi-paradigm programming language. C++ supports the same procedural programming paradigm as C language, and also supports object-oriented programming paradigm. STL (Standard Template Library) gives C++ a generic programming capability. Supporting multiple paradigms may be one of the reasons why C++ still has strong vitality until now.

Swift is a typical multi-paradigm programming language that supports object-oriented programming paradigm, functional programming paradigm, and generic programming. Swift's support for multiple programming paradigms is determined by its creation goals. The original intention of Swift was to provide a practical industrial language. It is different from Haskell, which is an academic programming language from universities and research institutions. Apple launched Swift with a clear business purpose: Objective-C, the main programming language of Mac OS and iOS systems, has become obsolete. Swift will enable developers of Apple systems to have a more modern programming language , thereby promoting Apple The healthy development of the entire ecosystem.

Imperative programming:

The main idea of imperative programming is to pay attention to the steps that the computer executes, that is, to tell the computer step by step what to do and then do .

In essence, it is an abstraction of the operating mechanism of the "von Neumann machine", and its programming thinking stems from the sequence of computer instructions .

(That is to say: The procedural language simulates the system structure of a computer machine, not based on the personal ability and tendency of the language user. We should be very clear about this, such as the assembly language of the single-chip microcomputer that we have used first .)

No matter if you are using C, C++ or C#, Java, Javascript, BASIC, Python, Ruby, etc., you can write in this way.

The program flow chart is an effective aid for programming in imperative language.

Imperative languages are particularly suitable for solving linear (or step by step) algorithmic problems . It emphasizes the "top-down (top-down)" and "excellent" design approach. This approach is very similar to our work and lifestyle, because our daily activities are carried out in a step-by-step order.

Imperative languages tend to develop programs that run faster and have a higher utilization of system resources . Imperative language is very flexible and powerful, and there are many classic application examples, which allows programmers to use it to solve a variety of problems.

The disadvantage of an imperative language is that it is not suitable for solving certain kinds of problems, such as those unstructured problems with complex algorithms . The problem is that an imperative language must specify an algorithm in detail, and it must also include the order in which these instructions or statements are executed. In fact, it is extremely difficult to give detailed algorithms to those unstructured problems with complex algorithms.

The place that has caused widespread controversy and discussion is: unconditional branching, or goto statement, which is an integral part of most procedural programming languages. Opponents claim that goto statement can be abused indefinitely; it provides an opportunity for program design to create confusion. . The current consensus is to keep it in most languages, and its dangers should be minimized through programming regulations.

The imperative processing of actual transactions can generally be divided into the following two modes:

  • Process-driven : It is similar to active polling. In the process of work, you have to be distracted and actively find work, so the free time is completely wasted

The vigilant person takes the initiative to poll, and his behavior depends on his own observation and judgment. It is process-driven and conforms to the conventional Flow-Driven Programming model.

  • Event-driven : For example, when the company has an oa system, you only need to check whether the oa system is assigned to you, and you can do your own thing. Don t worry about other things that you haven t done.

Using the entrusted person's passive notification (notification), the behavior depends on external emergencies, is event-driven, and conforms to the event-driven programming (Event-Driven Programming, referred to as EDP) model.

Event-driven programming

In fact, event-driven programming has been used in programming long before the appearance of the graphical user interface (GUI), but only when the graphical user interface became popular did it gradually evolve into a widely used programming design. mode.

In procedural programming, the code itself gives the order of program execution, although the order of execution may be affected by the input data of the program.

In event-driven programming, many parts of the program may be executed at completely unpredictable moments. Often the execution of these programs is triggered by the interaction between the user and the program being executed.

Event : is to notify that a certain event has occurred (the occurrence of an event is random).

Events and polling: The behavior of polling is to constantly observe and judge, and it is an endless way of behavior. The event is quietly waiting for things to happen. In fact, before the advent of Windows, PC applications that used the mouse to input character mode had to perform serial polling, and in this way to query and respond to different user operations.

Event handler : is a piece of program code executed when responding to an event. The event handler enables the program to respond to the user's behavior.

Event-driven is often used in the interaction between users and programs, interactive interaction through graphical user interfaces (mouse, keyboard, touchpad). Of course, it can also be used to handle exceptions and respond to user-defined events, etc.

Event exception handling is more complicated than user interaction .

Event-driven is not limited to GUI programming applications. But to achieve event-driven, we still need to consider more practical issues, such as: event definition, event triggering, event conversion, event merging, event queuing, event dispatching, event processing, event linkage and so on.

In fact, so far, we have not found a language and similar development environment for pure event-driven programming. All information about event-driven is based on GUI events.

The programming languages that are event-driven include: VB, C#, Java (GUI of Java Swing), etc. Most of the events they involve are GUI events.

This programming paradigm requires programmers to look at each problem with a step-by-step algorithm. Obviously, not every problem is suitable for this procedural way of thinking. This has also led to the emergence of other programming paradigms, including the object-oriented programming paradigm we are now introducing.

From the development history of programming to talk about the emergence of object-oriented. When the software is still very simple, we only need process-oriented programming:

Define function

Function one function two function three function four

Define the data

Data one data two data three data four

Finally, various functions, data operations.

When the software is developed, our software becomes larger and larger, the amount of code is more and more, and the complexity far exceeds Hello World, our writing is in trouble: functions and data will be defined very much, facing Two questions. The first is the naming conflict . There are only a few English words. There may be no suitable short words when writing names. In order to avoid conflicts, the function names can only be made longer and longer. Then there is code duplication . We can use the method of calling the function in the function, but the function call function (for example, one function has multiple methods (functions), and several functions are mixed) are not easy to maintain.

Object Oriented Program

Object-oriented programming (OOP) is a paradigm that supports object -oriented programming through classes, methods, objects, and message passing . Objects refer to instances of classes. It takes the object as the basic unit of the program and encapsulates the program and data to improve the reusability, flexibility and scalability of the software. The program in the object can access and frequently modify the data associated with the object . In object-oriented programming, programs are designed as objects that are related to each other .

Object-oriented programming can be regarded as a kind of idea that contains various independent and mutually calling objects in the program . This is just the opposite of the traditional idea: traditional programming advocates that the program is regarded as a collection of a series of functions, or directly It is a series of instructions given to the computer . Every object in object-oriented programming should be able to receive data, process data, and communicate data to other objects, so they can all be regarded as a small "machine", that is, an object. That is to leave things to the most suitable object to do.

The most intuitive analogy for the difference between object-oriented and process-oriented is the difference between wagging (dog tail) and dog. wagging tail () .

3.basic concepts of object-oriented programming:

Encapsulation , object-oriented programming hides the specific execution steps of a method, and instead transmits messages to it through a message passing mechanism. After in-depth thinking, a good abstraction is made, a "complete and minimal" interface is given, and the internal details can be hidden from the outside

Inheritance , under certain circumstances, a class will have "subclasses". The subclass is more specific than the original class (called the parent class);

Polymorphism , which refers to related different classes produced by inheritance, whose objects will respond differently to the same message;

Use object-oriented programming language, easy to build software model. Because, objects are very similar and seem to be easy to relate to all things and concepts in the real world.

Object-oriented through interface

Class , a class is a collection of similar objects. Things gather together-that is to say. Every object is an entity in its class. The objects in the class can receive the same message. In other words: a class contains and describes a set of objects that "have common characteristics (data elements) and common behaviors (functions)".

Interface , every object has an interface. An interface is not a class, but a set of specifications for classes that meet the requirements of the interface. The interface describes what the class should do but does not specify how to do it. A class can have one or more interfaces.

Method , method determines what kind of message an object can accept. Object-oriented design is sometimes simply summarized as "sending a message to an object".

On the one hand, object-oriented technology draws on the thinking methods of philosophy, psychology, and biology. On the other hand, it is based on other programming technologies and is a natural product of previous programming ideas.

If structured software design is the application of functional programming techniques to imperative languages for programming, object-oriented programming is just another way to apply functional models to imperative programs. At this time, modules are developed into objects. The process is condensed into the member method of the class. Many OOP technologies-abstract data types, information hiding, separation of interfaces and implementations, object generation functions, message passing mechanisms, etc., many things are owned by structured software design or appear separately in other programming languages. But only in object-oriented languages do they appear together, cooperating and complementing each other in a unique way of cooperation.

It can be seen from the above that if a car is designed according to a process-oriented approach, car manufacturers need to purchase a lot of parts, and then study how to debug and call this lot of parts to complete a function. However, if an object-oriented approach is used to design cars, then the car manufacturer can use outsourcing to hand it over to a professional brake system manufacturer for the design, and only need to agree on which public methods need to be opened, what inputs and outputs are all. In the three kinds of know almost kevin zou summed object-oriented manner :

Static function package object

Put together a batch of functions with related functions and encapsulate them into a class. This class can have no internal data at all, or it can have data. When there is data, these data actually act as configuration (configuration is transparent to a well-designed object. The internal function of the object itself does not know that there is configuration. It only knows that every piece of data it needs is in it. After that, it already exists in this, and you can take it and use it whenever you want. The way of configuration is given or obtained when you build the object (new). The characteristic of this object is that every function (or method) of it is right These data are read-only, so no matter whether the method is called, by whom, and how many times it is called, it will not change its state.

Domain model object

This concept is relative to the traditional database-oriented system analysis and design. Although the database describes the complex world with only foreign keys, the difficulty of software development lies in adapting to changes and being able to safely modify them. The relational model seems simple, but it wraps all tables and fields together like a spider web, and moves your whole body together. When you make changes, you will be like walking on thin ice. If you are not careful, you will lose sight of one another, and bugs one after another. The encapsulation feature of OO can just be used to solve this problem. Organize business data into independent objects so that their data can only be accessed by yourself. Basically, only some interfaces (methods) are left to the outside world, and none of the data will be made public unless absolutely necessary. The outside world can only send messages to it, and it responds to such messages by modifying its own data . This kind of object is just the opposite of the first kind of object. It must have data, and the purpose of each of its functions is to modify its own data. And every modification is coarse-grained, and after every modification, the object is still in the valid state. I recommend reading " Analysis of Domain Models " and " Domain Models, do you really understand it?"

Expansion by the way: Domain-Driven Design-Anemia Model-Domain Model-Congestion Model

Temporary object

Other small objects that are used to solve procedural development, super-many variables and super-complex processes. These objects work together to complete a function that can only be done by traditional procedural code of thousands of lines. For example, now you want to connect to the sql server to execute the query statement and get the result back. Do not use any class libraries and tools, all steps are performed by yourself, such as parsing protocol, socket network connection, data packet sending and receiving, etc. At this time, the functions are completed from beginning to end, and there is absolutely no first division of objects with clear responsibilities, so that it is easier for all objects to collaborate to complete this task.

But programming practice shows that not everything is a good thing to become an object. To give a crappy example in Java: In Java, only objects can be passed into functions as parameters (of course there are primitive types). So in order to pass a function to another function, you need to wrap the function in an object, usually an anonymous class, because this class has no other functions, just to make everything in Java happy for the design of the object.

Java has a pure object-oriented concept. From the beginning of its design, it hopes to model the world with a pure object model in which everything is an object. But until now, more and more non-object things have been added to Java. Introduced closures, thereby obtaining the first-order function in functional programming; introducing generics, thereby obtaining parameterized types. This may imply that the world is so rich and colorful that using a single model to model the world will not succeed .

Declarative programming:

Declarative programming is to express the logic of program execution in the form of data structures. Its main idea is to tell the computer what to do, but not to specify how to do it .

SQL statements are the most obvious example of declarative programming, for example:

SELECT * FROM collection WHERE num> 5

In addition to SQL, HTML and CSS used in web programming are also declarative programming.

By observing the code of declarative programming, we can find that it has a feature that it does not need to create variables to store data .

Another feature is that it does not contain loop control codes such as for, while .

Functional programming and declarative programming are related because their thinking is the same: that is, they only focus on what to do instead of how to do it. But functional programming is not limited to declarative programming.

Functional programming

Functional programming, or functional programming, functional programming, is a programming paradigm that treats computer operations as functional operations and avoids the use of program states and volatile objects. Among them, lambda calculus (lambda calculus) is the most important foundation of the language. Moreover, the function of calculus can accept function as input (argument) and output (outgoing value).

Functional programming is concerned with the relationship between types (algebraic structures), and imperative programming is concerned with the steps to solve the problem . Lambda in functional programming can be seen as the relationship between two types, an input type and an output type. Lambda calculus is to give a lambda expression an input type value, and then you can get an output type value. This is a calculation, and the calculation process satisfies the-equivalence and-statute. The thinking of functional programming is how to combine this relationship and use mathematical constructivism to construct the program you design.

Compared with imperative programming, functional programming emphasizes the results of program execution rather than the process of execution. It advocates the use of a number of simple execution units to make the calculation results progressive and derive complex calculations layer by layer, rather than designing a complex execution process .

Imperative programming is an abstraction oriented to computer hardware. There are variables (corresponding to storage units), assignment statements (acquisition and storage instructions), expressions (memory references and arithmetic operations) and control statements (jump instructions). In one sentence, commands A formula program is a sequence of instructions for a Von Neumann machine.

The function-oriented programming is a mathematical abstraction, it will be described as a calculation expression evaluation , a word, the function is a programming expression .

The most important feature of functional programming is "function first" , that is, functions can appear anywhere, for example, you can pass a function as a parameter to another function, not only that, you can also use a function as a return value.

The essence of functional programming

The term function in functional programming does not refer to a function in a computer (actually a Subroutine), but a function in exponential science, that is, the mapping of independent variables. That is to say, the value of a function is only determined by the value of the function parameter and does not depend on other states. For example, the sqrt(x) function calculates the square root of x. As long as x does not change, the value will remain the same no matter when it is called or how many times it is called.

In a functional language, a function, as a first-class citizen, can be defined anywhere, inside or outside the function, as the parameter and return value of the function, and the function can be combined.

A variable in a purely functional programming language is not a variable in an imperative programming language, that is, a unit that stores state, but a variable in algebra, that is, the name of a value. The value of a variable is immutable, which means that it is not allowed to assign a variable multiple times as in imperative programming languages . For example, in an imperative programming language, we write "x = x + 1", which relies on the fact that the state is mutable. It is correct when shown to the programmer, but when shown to the mathematician, the equation is considered to be false. .

Functional languages such as conditional statements and loop statements are not control statements in imperative programming languages, but syntactic sugar of functions . For example, in Scala language, if else is not a statement but a ternary operator, which has a return value. .

Strictly functional programming means programming without using variable variables, assignments, loops, and other imperative control structures .

Theoretically speaking, functional languages are not run on machines with von Neumann architecture, but run through lambda calculus , which is through variable substitution. Variables are replaced by their values or expressions. Functions Also replace it with its expression, and perform calculations based on the operator. Lambda calculus is Turing completeness, but in most cases, functional programs are compiled into machine language (von Neumann machine) instructions for execution .

Features of functional programming

  • Functions are "first-class citizens": functions take precedence, just like other data types.
  • Only use "expression" instead of "statement": get a return value through the calculation process of expression, instead of modifying a certain state through a statement.
  • No side effects: Variables are not polluted, and the same input will always get the same data.
  • Immutability: As mentioned earlier, a new value is returned without modifying the variable.

Since the variable value is immutable, the operation of the value is not to modify the original value, but to modify the newly generated value. The original value remains inconvenient. Generally speaking, algorithms have two definitions: iterative and recursive.

Because variables are immutable, pure functional programming languages cannot implement loops. This is because For loops use variable states as counters, while While loops or DoWhile loops require variable states as a condition for jumping out of the loop. Therefore, in functional languages, recursion can only be used to solve the iteration problem, which makes functional programming rely heavily on recursion.

Of course, functional languages still have the following features:

  • Higher-order function (Higher-order function) : is a function whose parameter is a function or whose return value is a function. With higher-order functions, the granularity of reuse can be reduced to the function level. Compared with object-oriented languages, the granularity of reuse is lower.
  • Partially Applied Functions : A function receives a function with multiple parameters and returns a function that requires fewer parameters. The partial function fixes one or more parameters internally, and then returns a new function. The returned function receives the remaining parameters to complete the application of the function.
  • Currying : Enter a function with multiple parameters, and return a function that only accepts a single parameter.
  • Closure : A closure is a function that has the right to access variables in the scope of another function. The three characteristics of a closure: 1. A closure is a function defined in a function. 2. The closure can access the variable containing the function. 3. Even if the containing function is executed, the variable referenced by the closure will not be released. See " Gossip Closure " for details

    Benefits of functional programming

    Since imperative programming languages can also implement higher-order functions in a similar manner to function pointers, the main benefit of functional programming is mainly brought about by immutability. Without mutable state, the function is referential transparency and no side effect (No Side Effect) .

The function does not depend on the external state and does not modify the external state. The result of the function call does not depend on the time and location of the call. The code written in this way is easy to reason and not easy to make mistakes. This makes unit testing and debugging easier.

Since the state is not shared (between multiple threads), there will be no race condition, and there is no need to use locks to protect the mutable state, and there will be no deadlocks , which can be better concurrency , Especially under the symmetric multi-processor (SMP) architecture, it can better utilize the parallel processing capabilities provided by multiple processors (cores).

I think the benefits of functional programming don t care about the damn this point in js

Functional programming languages also provide lazy evaluation-Lazy evaluation , also known as call-by-need, is when the expression is assigned to a variable (or called binding) without calculating the value of the expression, and in the variable section The calculation is performed only when it is used once. This can improve performance by avoiding unnecessary evaluations.

Functional programming languages generally also provide powerful pattern matching (Pattern Match) functions. Algebraic data types can be defined in functional programming languages, and new data types can be formed by combining existing data types. For example, case classes are provided in Scala, and the values of algebraic data types can be analyzed through pattern matching.

Functional programming is inherently compatible with unit testing (especially black box testing), because FP focuses on input and output. In contrast to Java or C++, just checking the return value of a function is not enough: the code may modify the external state value, so we also need to verify the correctness of these external state values. In the FP language, there is no need at all.

In terms of debugging, because the error in the FP program does not depend on the irrelevant code that has been run before. In an imperative program, a bug may sometimes be able to reproduce and sometimes not. Because the operation of these functions depends on some external states, and these external states need to be modified by some code that is completely unrelated to this bug through a special execution flow. In FP, this situation does not exist at all: if the return value of a function is wrong, it will always be wrong, no matter what code you have run before. And the whole program is Function Solitaire.

Recommended reading " Functional Programming for Dummies "

Generic programming

Generic programming is another interesting topic. Generics provide a higher level of abstraction for programming languages, namely parameterized types. In other words, it is to abstract the type information in an algorithm or class originally specific to a certain type. This abstracted concept is the template in the STL (Standard Template Library) of C++. STL shows the power of generic programming, and has become a powerful weapon of C++ as soon as it appears. In addition to C++, C#, Java, Haskell and other programming languages have introduced the concept of generics.

Generic programming is a slightly more partial concept, it only involves how to deal with types more abstractly, that is, parameterized types. This is not enough to support the core concepts of a language. We will not hear that a programming language is purely generic programming, and there is no other programming paradigm. But just because generics do not change the core of the programming language, it can be well integrated into other programming methods most of the time. C++, Scala, Haskell and other programming languages with different styles all support generics. Generic programming provides a higher level of abstraction, which means stronger expressive ability. This is a delicious meal and wine for most programming languages.

In Swift, generics are widely used, and many Swift standard libraries are built through generic code. For example, Swift's array and dictionary types are both generic sets. Such examples can be seen everywhere in Swift.

Reference article: