Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

On programming Paradigm-the thought behind programming language

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Programming paradigm

Thomas。 After Kuhl proposed the paradigm theory of "scientific revolution", Robert Floyd used the word programming paradigm in the Turing Award presentation speech in 1979. The programming paradigm generally includes three aspects, taking OOP as an example:

1, the logical system of the discipline-rule paradigm: such as class / object, inheritance, dynamic binding, method rewriting, object replacement and so on.

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

3. Nature view / world view-concept paradigm: emphasizes the organization technology of the program, regards the program as a loosely coupled combination of objects / classes, and organizes the classes into a hierarchical structure by inheritance mechanism. program operation is regarded as a dialogue between objects that serve each other.

Simply put, the programming paradigm is the programmer's view of what the program should have, and represents the programmer's view of how the program should be built and executed.

Common programming paradigms are: imperative, procedural, declarative, object-oriented, functional, generic programming and so on.

Imperative- imperative | | procedural |

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

Script Perl Python PHP, which "glue together" independent programs developed in other languages as parts

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

Declarative- declarative | | declarative

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

Data flow ld Val, the language regards computing as the flow of information between some basic functional nodes. The node is triggered by the arrival of input words and can operate concurrently.

A logical Prolog that tries to find values that satisfy certain relationships according to a set of logical rules

Template-based XSLT xml html

It should be reminded that the programming paradigm is a classification of programming languages, and it is not specific to a particular programming language. As far as programming languages are concerned, one language can be applied to multiple programming paradigms.

Some programming languages are specifically designed for a particular paradigm, such as C is a procedural programming language; Smalltalk and Java are pure object-oriented programming languages; and Haskell is a purely functional programming language. Other programming languages do not correspond to programming paradigms one by one, such as Python,Scala,Groovy, which supports object-oriented and functional programming to some extent. C++ is a successful example of multi-paradigm programming languages. C++ supports the same procedural programming paradigm as C language, but also supports the object-oriented programming paradigm. STL (Standard Template Library) makes C++ have the ability of generic programming. 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, which supports both object-oriented programming paradigm, functional programming paradigm and generic programming. The fact that Swift supports multiple programming paradigms is determined by its creative goals. The original intention of Swift is to provide a practical industrial language. It is different from Haskell, which is an academic programming language from universities and research institutions. Swift comes out with a clear commercial purpose: Mac OS and Objective-C, the main programming language of iOS systems, have grown old, and Swift will enable Apple system developers to have a more modern programming language, thus promoting the healthy development of Apple's entire ecosystem.

Imperative programming:

The main idea of imperative programming is to focus on the steps that the computer performs, that is, telling the computer what to do first and then what to do step by step.

In essence, it is Feng. The abstraction of the operating mechanism of Neumann machine, and its programming thinking comes from the sequential arrangement of computer instructions.

That is to say, procedural language simulates the system structure of computer machines, not based on the personal abilities and tendencies of language users. We should be very clear about this, such as the assembly language of the single-chip microcomputer that we used in the first place. )

Whether you are using C, C++ or caching, Java, Javascript, BASIC, Python, Ruby, etc., you can write in this way.

Program flow chart is an effective auxiliary means 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 "Excelsior" design approach. This way is very similar to our work and life style, because our daily activities are carried out in a step-by-step order.

Imperative languages tend to develop programs that run fast and have high 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 imperative language is that it is not suitable for solving some kinds of problems, such as unstructured problems with complex algorithms. The problem is that the imperative language must describe an algorithm in detail and include the order in which these instructions or statements are executed. In fact, it is extremely difficult to give detailed algorithms for unstructured problems with complex algorithms.

What is widely controversial and discussed is the unconditional branch, or goto statement, which is part of most procedural programming languages, and opponents claim that goto statements can be infinitely abused; it provides programming with the opportunity to create confusion. The current consensus is that it should be retained in most languages and that its dangers should be minimized through programming regulations.

Imperative processing of actual things can generally be divided into the following two modes:

Process-driven: similar to active polling, you have to be distracted to find a job in your work, so that your spare time is completely wasted.

The vigilant active polling (polling), whose behavior depends on one's own observation and judgment, is process-driven and conforms to the conventional process-driven programming (Flow-Driven Programming) model.

Event-driven: for example, the company has an oa system, and when you finish your work, you just need to see if the oa system is assigned to you. There's nothing you can do. Don't worry about other things that haven't been done yet.

Using entrusting passive equal notification (notification), the behavior depends on external emergencies, is event-driven, and conforms to the mode of event-driven programming (Event-Driven Programming, referred to as EDP).

Event-driven programming

In fact, event-driven programming has been used in programming long before the emergence of graphical user interface (GUI), but it has gradually evolved into a widely used programming pattern only when the graphical user interface is widely popular.

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

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

Event: is to notify that a particular event has happened (the event is random).

Events and polling: the behavior of polling is constant observation and judgment, which is an endless way of behavior. And the event is quietly waiting for it to happen. In fact, before the advent of Windows, PC applications that used mouse input character mode had to do serial polling and query and respond to different user actions in this way.

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

Event driver is often used for the interaction between users and programs, through the graphical user interface (mouse, keyboard, touchpad) for interactive interaction. Of course, it can also be used for exception handling and responding to user-defined events, and so on.

Exception handling of events is more complex than user interaction.

Event drivers are not limited to GUI programming applications. However, to achieve event-driven, we also need to consider more practical problems, such as: event definition, event trigger, event transformation, event merging, event queuing, event dispatching, event handling, event connection and so on.

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

Event-driven programming languages are: VB, C #, Java (GUI of Java Swing), and so on. The vast majority of the events involved are GUI events.

This programmatic 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 led to the emergence of other programming paradigms, including the object-oriented programming paradigm we are now introducing.

Talk about the emergence of object-oriented from the development history of programming. When the software was very simple, we only needed process-oriented programming:

Define function

Function one function two function three function four

Define data

Data one data two data three data four

Finally, the operation of various functions and data.

When the software is developed, our software becomes larger and larger, the amount of code is more and more, and the complexity is much more than Hello World, we will have trouble writing: functions and data will be defined very much, facing two problems. First of all, the naming conflict, there are only a few English words, it may be written that there are no suitable short words to be used, in order to avoid conflicts, we can only get longer and longer function names. Then there is code repetition, we can use the method of calling the function in the function, but the function adjustment function (for example, a function with multiple methods (functions), several function mixed methods) is not easy to maintain.

Object-oriented program

Object-oriented programming (Object-oriented programming OOP) is a paradigm that supports object-oriented programming through classes, methods, objects and message passing. An object refers to an instance of a class. It takes the object as the basic unit of the program and encapsulates the program and data in order to improve the reusability, flexibility and expansibility of the software. the program in the object can access and often modify the data related to the object. In object-oriented programming, programs are designed to be related to each other.

Object-oriented programming can be regarded as an idea that contains all kinds of independent objects that call each other in the program, which is contrary to the traditional idea: the traditional programming advocates that the program should be regarded as a collection of a series of functions. or directly a series of instructions to the computer. Every object in object-oriented programming should be able to accept data, process data, and communicate data to other objects, so they can be regarded as a small "machine", that is, objects. That is, to leave things to the most suitable person to do.

The most intuitive metaphors for the difference between object-oriented and process-oriented are wagging a dog's tail and a dog. The difference between wagging tail ().

Three basic concepts of object-oriented programming:

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

Inheritance, in some cases, a class will have "subclasses". The subclass is more specific than the original class (called the parent class)

Polymorphism refers to different classes related to inheritance, whose objects respond differently to the same message.

Using object-oriented programming language, it is easy to build software model. Because, objects are very similar and seem easy to do with all things and concepts in the real world.

Object-oriented through interface

Class, which is a collection of similar objects. Birds of a feather flock together. Each object is an entity in its class. Objects in the class can accept the same message. In other words: a class contains and describes a set of objects that "share common characteristics (data elements) and common behavior (functions)."

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

Method, which determines what kind of message an object can accept. Object-oriented design is sometimes simply summed up as "sending messages to objects".

On the one hand, object-oriented technology draws lessons from the way of thinking 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 to apply functional programming technology to imperative language for programming, object-oriented programming is just another way to apply functional model to imperative programming. At this time, the module evolves into objects and the process shrinks to the member methods of class. Many of the technologies of OOP-abstract data types, information hiding, interface and implementation separation, object generation, messaging mechanisms, etc., are owned by structured software design or appear separately in other programming languages. But only in object-oriented languages do they appear together and cooperate and complement each other in a unique way of cooperation.

As can be seen from the above, if the car is designed according to the process-oriented approach, the automobile manufacturer needs to purchase a lot of parts, and then study how to debug and invoke this large number of parts to complete a function. However, if the object-oriented method is used to design the car, then the automobile manufacturer can outsource the design to a professional brake system manufacturer, and only need to agree on which public methods need to be opened and what input and output.

Three object-oriented approaches summarized by Zhihu kevin zou:

Static function package object

Encapsulate a batch of functionally related functions together into a class. This category can have no internal data at all, or it can have data. When there is data, this data actually acts as configuration (configuration is transparent to a well-designed object, the function inside the object itself does not know that there is configuration at all, it only knows that every data it needs has been stored in this after its new, and can be used at will. The characteristic of this object is that each of its functions (or methods) is read-only to this data, so no matter whether the method is called or not, 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 only uses foreign keys to describe the complex world, the difficulty of software development is to adapt to changes and can be safely modified. The relationship model seems simple, but it wraps all the table and fields together like a cobweb, affecting the whole body, making you tread on thin ice when you modify it, and you will lose sight of one or the other, and bug will rise and fall one after another. The encapsulation feature of OO can be used to solve this problem. Organize the business data into separate objects so that their data can only be accessed by themselves. Basically, there are only some interfaces (methods) left to the outside world, and none of the data will be made public unless they have to. The outside world can only send messages to it, and it responds to such messages by modifying its own data. This object is the opposite of the first object, it must have data, and each of its functions exists to modify its own data. And each modification is coarse-grained, and after each modification, the object is still in the valid state. It is recommended to read "Domain Model Analysis" and "Domain Model, do you really understand it? "

By the way: domain driven design (Domain-Driven Design)-anemia model-domain model-hyperemia model

Temporary object

Other small objects sorted out by too many variables and super-complex processes during program development. These objects work together to complete a function that can only be accomplished by thousands of lines of traditional procedural code. For example, now you need to connect to sql server to execute the query and get the result back. Do not use any class libraries and tools, all the steps are carried out on their own, such as parsing protocol, socket network connection, packet sending and receiving and so on. At this time, it is done with functions from beginning to end, and there is absolutely no first division of objects with distinct responsibilities, so it is easier for each object to work together to accomplish this task.

But programming practice shows that not everything is a good thing to be an object. Take a poor example in Java: only objects in Java can be passed into functions as arguments (and of course the original type primitive type). So in order to pass the function to another function, you need to wrap the function in an object, usually using an anonymous class, because this class does nothing else, 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 wants to model the world with a pure object model in which everything is an object. But up to now, more and more non-object things have been added to Java. Closures are introduced to obtain first-order functions in functional programming, and generics are introduced to obtain parameterized types. This may imply that the world is so colorful that modeling the world with a single pattern will not be successful.

Declarative programming:

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

The SQL statement is the most obvious example of declarative programming, such as:

SELECT * FROM collection WHERE num > 5

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

By looking at declarative programming code, we can see that one feature of it is that it does not need to create variables to store data.

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

Functional programming and declarative programming are related because they have the same idea: focus on what to do rather than how to do it. But functional programming is not limited to declarative programming.

Functional programming

Functional programming (functional programming), or functional programming or functional programming, is a programming paradigm that regards computer operations as functional operations and avoids the use of program states and variable objects. Among them, λ calculus (lambda calculus) is the most important foundation of the language. Moreover, the function of λ calculus can accept the 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 problem-solving steps. Lambda in functional programming can be seen as a relationship between two types, an input type and an output type. Lambda calculus is to give the lambda expression a value of input type, then you can get a value of output type, which is a calculation, the calculation process satisfies-equivalence and-specification. The idea 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 result of program execution rather than the process of execution, advocating the use of several simple execution units to make the calculation results gradually and derive complex operations layer by layer, rather than designing a complex execution process.

Imperative programming is an abstraction oriented to computer hardware, with variables (corresponding to storage units), assignment statements (acquisition, storage instructions), expressions (memory references and arithmetic operations) and control statements (jump instructions). An imperative program is a sequence of instructions of a von Neumann machine.

Functional programming is an abstraction oriented to mathematics, which describes computation as a kind of expression evaluation. In a word, a functional program is an expression.

The most important feature of functional programming is "function first", that is, a function can appear anywhere, for example, you can pass a function as an argument 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 Subroutine), but to a function in mathematics, that is, the mapping of independent variables. In other words, the value of a function is determined only by the value of the function's parameters and does not depend on other states. For example, the sqrt (x) function calculates the square root of x. As long as x remains the same, the value remains the same no matter when or how many times it is called.

In the functional language, the 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 pure 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 (immutable), which means that you are 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 depends on the fact that the variable state is correct for programmers, but for mathematicians, the equation is considered false.

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

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

In theory, functional languages are not run on machines with von Neumann architecture, but through λ calculus, that is, through variable substitution, variables are replaced with their values or expressions, and functions are also replaced by their expressions and calculated according to operators. The lambda calculus is Turing completeness, but in most cases, functional programs are executed by instructions compiled into the machine language.

The characteristics of functional programming

Functions are "first-class citizens": functions take precedence, just like other data types.

Use only "expressions", not "statements": get a return value through the expression (expression) evaluation process, rather than modify a state through a statement (statement).

No side effects: no pollution variables, the same input will always get the same data.

Immutability: as mentioned earlier, do not modify the variable and return a new value.

Because the value of the variable is immutable, the operation of the value is not to modify the original value, but to modify the newly generated value, which is inconvenient to maintain.

Generally speaking, algorithms have two definitions: iterative and recursive.

Pure functional programming languages cannot implement loops because variables are immutable, because For loops use variable states as counters, while While or DoWhile loops need mutable states as a condition to jump out of the loop. Therefore, recursion can only be used to solve iterative problems in functional languages, which makes functional programming heavily dependent on recursion.

Functional languages, of course, have the following features:

Higher order function (Higher-order function): a function whose parameter is a function or whose return value is a function. With high-order functions, the granularity of reuse can be reduced to the function level, and the granularity of reuse is lower than that of object-oriented languages.

Partial application function (Partially Applied Functions): a function takes a function with multiple arguments and returns a function that requires fewer arguments. The partial function fixes one or more parameters internally, then returns the new function, and the returned function receives the remaining parameters to complete the application of the function.

Currying: enter a function with multiple arguments and return a function that takes only a single argument.

Closure: a closure is a function that has access to variables in the scope of another function. There are three characteristics of closure: 1. A closure is a function defined in a function. two。 Closures can access variables that contain functions. 3. Even if the containing function is finished, the variables referenced by the closure will not be released. For more information, see "gossip closure"

Benefits of functional programming

Because imperative programming languages can also implement high-order functions in a way similar to function pointers, the main benefits of functions are mainly brought by immutability. Without mutable state, the function simply refers to Referential transparency and has no No Side Effect.

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

Because the state is not shared (among threads), there is no Race condition, there is no need for locks to protect variable state, and deadlocks do not occur, so that concurrency can be better achieved, especially in the symmetric multiprocessor (SMP) architecture.

I think the advantage of functional programming is that it doesn't matter the damn this pointing in js.

Functional programming languages also provide lazy evaluation-Lazy evaluation, also known as call-by-need, which does not evaluate an expression when it is assigned to a variable (or binding), but only when the variable is first used. In this way, performance can be improved by avoiding unnecessary evaluations.

Functional programming languages generally also provide powerful pattern matching (Pattern Match) capabilities. Algebraic data types (Algebraic data type) can be defined in functional programming languages. By combining existing data types to form new data types, such as providing case class in Scala, the values of algebraic data types can be analyzed by 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 clocked values, it is not enough to just check the return value of the function: the code may modify the external state values, so we also need to verify the correctness of these external state values. In FP language, it is not needed at all.

Debug the error-checking aspect because errors in FP programs do not depend on irrelevant code that has been run before. In an imperative program, a bug may sometimes be reproduced and sometimes not. Because the operation of these functions depends on some external state, which in turn needs to be modified by some code that has nothing to do with the bug through a special execution process. This is not true at all in FP: if the return value of a function goes wrong, it will always go wrong, no matter what code you ran before. And the whole program is a function connection.

It is recommended to read "functional programming for fools"

Generic programming

Generic programming is another interesting topic. Generics provide a higher level of abstraction for programming languages, that is, parameterized types. In other words, it abstracts the type information from an algorithm or class that is originally specific to a certain type. This abstract concept in C++ 's STL (Standard Template Library) is Template. STL demonstrated the power of generic programming and became a powerful weapon for C++ as soon as it appeared. In addition to C++, programming languages such as Clipper, Java, and Haskell have introduced the concept of generics.

Generic programming is a slightly more local concept that only involves how to deal with types more abstractly, that is, parameterized types. This is not enough to support the core concept of a language. We will not hear that a programming language is pure generic programming without other programming paradigms. But just because generics do not change the core of the programming language, most of the time, it can be well integrated into other programming methods. Generics are supported by programming languages that are very different in style, such as Caterpillar, Scala, and Haskell. Generic programming provides a higher level of abstraction, which means greater expressiveness. This is a delicious meal and wine for most programming languages.

Generics are widely used in Swift, and many Swift standard libraries are built from generic code. For example, the array and dictionary types of Swift are generic sets. Such examples can be found everywhere in Swift.

Original link: talk again about the programming paradigm-the idea behind the program language-model design, domain design, software design, Zhou Jun's personal website, and then talk about the series are all brick summary articles, there is something wrong with the text, please leave a message, thank you!

Reference article:

Programming paradigm [programmer's programming worldview]

Hanoi Tower-- the solution of various programming paradigms

Programming paradigms: imperative programming (Imperative), declarative programming (Declarative) and functional programming (Functional)

Magical λ Calculus https://www.cnblogs.com/dragonpig/archive/2010/01/26/1657052.html

Programming language paradigm http://www.cnblogs.com/lisperl/archive/2011/11/20/2256165.html

λ calculus learning https://www.cnblogs.com/kirohuji/p/7080876.html

Talking about https://cloud.tencent.com/developer/article/1190773 in functional programming

Most of this article is a summary of the link text given in this article. If there is anything wrong, please leave a message on this site, let us know, thank you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report