Mis täpselt on programmeerimisparadigma?

Iga loll saab kirjutada koodi, millest arvuti saab aru. Head programmeerijad kirjutavad inimestele arusaadava koodi.

- Martin Fowler

Programmeerimisel on alati vaenlane keerukus. Suure keerukusega, paljude liikuvate osade ja üksteisest sõltuvate komponentidega programmid tunduvad esialgu muljetavaldavad. Kuid võime tõlkida tegelikust probleemist lihtne või elegantne lahendus eeldab sügavamat mõistmist.

Rakenduse väljatöötamisel või lihtsa probleemi lahendamisel ütleme sageli: "Kui mul oleks rohkem aega, oleksin kirjutanud lihtsama programmi". Põhjus on see, et tegime suurema keerukusega programmi. Mida vähem keerukust meil on, seda lihtsam on siluda ja aru saada. Mida keerukamaks programm muutub, seda raskem on sellega töötada.

Keerukuse haldamine on programmeerija peamine mure . Kuidas siis programmeerijad keerukusega toime tulla? On palju üldisi lähenemisviise, mis vähendavad programmi keerukust või muudavad selle hallatavamaks. Üks peamisi lähenemisviise on programmeerimisparadigma. Sukeldume programmeerimisparadigmadesse!

Sissejuhatus programmeerimisparadigmadesse

Termin programmeerimisparadigma viitab programmeerimisstiilile . See ei viita konkreetsele keelele, vaid pigem programmeerimisviisile.

Programmeerimiskeeli on palju, kuid need kõik peavad rakendamisel järgima mõnda strateegiat. Ja see strateegia on paradigma.

Programmeerimisparadigmade tüübid

Imperatiivne programmeerimisparadigma

Sõna „imperatiiv” tuleneb ladina keelest „impero”, mis tähendab „ma käsin”.

See on sama sõna, millest saame "keisri", ja see on üsna tabav. Sa oled keiser. Annate arvutile vähe korraldusi teha ja see teeb neid ükshaaval ja annab aru.

Paradigma koosneb mitmest väitest ja pärast kõigi nende täitmist tulemus salvestatakse. See seisneb juhiste loendi koostamises, et öelda arvutile, mida samm-sammult teha.

Imperatiivses programmeerimisparadigmas on sammude järjekord ülioluline, sest antud sammul on erinevad tagajärjed sõltuvalt muutujate praegustest väärtustest, kui samm on täidetud.

Selle illustreerimiseks leiame imperatiivse paradigma käsitluses esimese kümne loodusarvu summa.

Näide C-s:

#include  int main() { int sum = 0; sum += 1; sum += 2; sum += 3; sum += 4; sum += 5; sum += 6; sum += 7; sum += 8; sum += 9; sum += 10; printf("The sum is: %d\n", sum); //prints-> The sum is 55 return 0; }

Ülaltoodud näites kamandame arvutit, mida teha rida realt. Lõpuks salvestame väärtuse ja printime selle.

1.1 Protseduurilise programmeerimise paradigma

Protseduuriline programmeerimine (mis on samuti hädavajalik) võimaldab jaotada need juhised protseduurideks .

MÄRKUS. Protseduurid pole funktsioonid. Nende erinevus seisneb selles, et funktsioonid tagastavad väärtuse ja protseduurid mitte. Täpsemalt öeldes on funktsioonid kavandatud nii, et neil oleks minimaalsed kõrvalmõjud ja nad tooksid alati sama sisendi, kui neile antakse sama sisend. Seevastu protseduuridel pole mingit tagasiväärtust. Nende peamine eesmärk on antud ülesande täitmine ja soovitud kõrvalmõju tekitamine.

Suurepärane näide protseduuridest oleks loopi jaoks hästi tuntud. For loopi peamine eesmärk on põhjustada kõrvaltoimeid ja see ei tagasta väärtust.

Illustreerimiseks leiame protseduurilise paradigma lähenemisviisist esimese kümne loomuliku arvu summa.

Näide C-s:

#include  int main() { int sum = 0; int i =0; for(i=1;i The sum is 55 return 0; }

Ülaltoodud näites oleme esimese kümne loodusarvu liitmise leidmiseks kasutanud funktsiooni simple for loop.

Protseduurilise programmeerimise paradigmat toetavad keeled on järgmised:

  • C
  • C ++
  • Java
  • ColdFusion
  • Pascal

Protseduuriline programmeerimine on sageli parim valik, kui:

  • Toimub keeruline toiming, mis sisaldab sõltuvust toimingute vahel ja kui on vaja erinevate rakenduse olekute („SQL laadimine”, „SQL laaditud”, „Võrgu võrgus”, „Heli riistvara puudub” jne) selge nähtavus. Tavaliselt sobib see rakenduse käivitamisel ja väljalülitamisel (Holligan, 2016).
  • Programm on väga ainulaadne ja vähe elemente jagati (Holligan, 2016).
  • Programm on staatiline ja eeldatavasti ei muutu see aja jooksul palju (Holligan, 2016).
  • Eeldatakse, et projekti aja jooksul ei lisata ühtegi või ainult mõned funktsioonid (Holligan, 2016).

Miks peaksite kaaluma protseduurilise programmeerimise paradigma õppimist?

  • See on lihtne.
  • Lihtsam viis programmivoo jälgimiseks.
  • Sellel on võime olla tugevalt modulaarne või struktureeritud.
  • Vajab vähem mälu: see on tõhus ja tõhus.

1.2 Objektorienteeritud programmeerimise paradigma

OOP on kõige populaarsem programmeerimisparadigma oma ainulaadsete eeliste tõttu, nagu koodi modulaarsus ja võime seostada reaalses maailmas äriprobleeme koodi järgi.

Objektorienteeritud programmeerimine pakub jätkusuutlikku viisi spagetikoodi kirjutamiseks. See võimaldab teil programme täiendada plaastrite seeriana.

- Paul Graham

Objektorienteeritud programmeerimise põhiomaduste hulka kuuluvad klass, abstraktsioon, kapseldamine, pärilikkus ja polümorfism.

Klassi on malli või plaan, millest objektid loodud.

Objektid on klasside eksemplarid. Objektidel on atribuudid / olekud ja meetodid / käitumisviisid. Atribuudid on objektiga seotud andmed, meetodid aga toimingud / funktsioonid, mida objekt saab teha.

Abstraktsioon eraldab liidese rakendamisest. Kapseldamine on objekti sisemise rakenduse varjamise protsess.

Pärand võimaldab hierarhilisi suhteid esindada ja täpsustada. Polümorfism võimaldab erinevat tüüpi objektidel saada sama sõnumit ja reageerida erineval viisil.

Selle illustreerimiseks leidkem objektorienteeritud paradigma käsitluses esimese kümne loodusarvu summa.

Näide Java-s:

public class Main { public static void main(String[] args) { Addition obj = new Addition(); obj.num = 10; int answer = obj.addValues(); System.out.println("The sum is = "+answer); //prints-> The sum is 55 } } class Addition { int sum =0; int num =0; int addValues(){ for(int i=1; i<=num;i++){ sum += i; } return sum; } }

Meil on klass, Additionmillel on kaks olekut sumja nummis lähtestatakse nulli. Meil on ka meetod, addValues()mis tagastab numarvude summa .

Kui Mainklassi, oleme loonud objekti, objlisamise klassi. Seejärel oleme initsialiseerinud numväärtuse 10 ja addValues()summa välja saamiseks kasutasime meetodit.

Objektorienteeritud paradigmat toetavad keeled:

  • Python
  • Rubiin
  • Java
  • C ++
  • Smalltalk

Objektorienteeritud programmeerimist saab kõige paremini kasutada siis, kui:

  • Teil on mitu programmeerijat, kes ei pea igast komponendist aru saama (Holligan, 2016).
  • Seal on palju koode, mida saaks jagada ja uuesti kasutada (Holligan, 2016).
  • Eeldatakse, et projekt muutub sageli ja aja jooksul lisandub (Holligan, 2016).

Miks peaksite kaaluma objektorienteeritud programmeerimisparadigma õppimist?

  • Reuse of code through Inheritance.
  • Flexibility through Polymorphism.
  • High security with the use of data hiding (Encapsulation) and Abstraction mechanisms.
  • Improved software development productivity: An object-oriented programmer can stitch new software objects to make completely new programs (The Saylor Foundation, n.d.).
  • Faster development: Reuse enables faster development (The Saylor Foundation, n.d.).
  • Lower cost of development: The reuse of software also lowers the cost of development. Typically, more effort is put into the object-oriented analysis and design (OOAD), which lowers the overall cost of development (The Saylor Foundation, n.d.).
  • Higher-quality software: Faster development of software and lower cost of development allows more time and resources to be used in the verification of the software. Object-oriented programming tends to result in higher-quality software (The Saylor Foundation, n.d.).

1.3 Parallel processing approach

Parallel processing is the processing of program instructions by dividing them among multiple processors.

A parallel processing system allows many processors to run a program in less time by dividing them up.

Languages that support the Parallel processing approach:

  • NESL (one of the oldest ones)
  • C
  • C++

Parallel processing approach is often the best use when:

  • You have a system that has more than one CPU or multi-core processors which are commonly found on computers today.
  • You need to solve some computational problems that take hours/days to solve even with the benefit of a more powerful microprocessor.
  • You work with real-world data that needs more dynamic simulation and modeling.

Why should you consider learning the parallel processing approach?

  • Speeds up performance.
  • Often used in Artificial Intelligence. Learn more here: Artificial Intelligence and Parallel Processing by Seyed H. Roosta.
  • It makes it easy to solve problems since this approach seems to be like a divide and conquer method.

Here are some useful resources to learn more about parallel processing:

  1. Parallel Programming in C by Paul Gribble
  2. Introduction to Parallel Programming with MPI and OpenMP by Charles Augustine
  3. INTRODUCTION TO PARALLEL PROGRAMMING WITH MPI AND OPENMP by Benedikt Steinbusch

2. Declarative programming paradigm

Declarative programming is a style of building programs that expresses the logic of a computation without talking about its control flow.

Declarative programming is a programming paradigm in which the programmer defines what needs to be accomplished by the program without defining how it needs to be implemented. In other words, the approach focuses on what needs to be achieved instead of instructing how to achieve it.

Imagine the president during the state of the union declaring their intentions for what they want to happen. On the other hand, imperative programming would be like a manager of a McDonald's franchise. They are very imperative and as a result, this makes everything important. They, therefore, tell everyone how to do everything down to the simplest of actions.

So the main differences are that imperative tells you how to do something and declarative tells you what to do.

2.1 Logic programming paradigm

The logic programming paradigm takes a declarative approach to problem-solving. It's based on formal logic.

The logic programming paradigm isn't made up of instructions - rather it's made up of facts and clauses. It uses everything it knows and tries to come up with the world where all of those facts and clauses are true.

For instance, Socrates is a man, all men are mortal, and therefore Socrates is mortal.

The following is a simple Prolog program which explains the above instance:

 man(Socrates). mortal(X) :- man(X). 

The first line can be read, "Socrates is a man.'' It is a base clause, which represents a simple fact.

The second line can be read, "X is mortal if X is a man;'' in other words, "All men are mortal.'' This is a clause, or rule, for determining when its input X is "mortal.'' (The symbol ":-'', sometimes called a turnstile, is pronounced "if''.) We can test the program by asking the question:

 ?- mortal(Socrates). 

that is, "Is Socrates mortal?'' (The "?-'' is the computer's prompt for a question). Prolog will respond "yes''. Another question we may ask is:

?- mortal(X).

That is, "Who (X) is mortal?'' Prolog will respond "X = Socrates''.

To give you an idea, John is Bill's and Lisa's father. Mary is Bill's and Lisa's mother. Now, if someone asks a question like "who is the father of Bill and Lisa?" or "who is the mother of Bill and Lisa?" we can teach the computer to answer these questions using logic programming.

Example in Prolog:

/*We're defining family tree facts*/ father(John, Bill). father(John, Lisa). mother(Mary, Bill). mother(Mary, Lisa). /*We'll ask questions to Prolog*/ ?- mother(X, Bill). X = Mary 

Example explained:

father(John, Bill).

The above code defines that John is Bill's father.

We're asking Prolog what value of X makes this statement true? X should be Mary to make the statement true. It'll respond X = Mary

?- mother(X, Bill). X = Mary 

Languages that support the logic programming paradigm:

  • Prolog
  • Absys
  • ALF (algebraic logic functional programming language)
  • Alice
  • Ciao

Logic programming paradigm is often the best use when:

  • If you're planning to work on projects like theorem proving, expert systems, term rewriting, type systems and automated planning.

Why should you consider learning the logic programming paradigm?

  • Easy to implement the code.
  • Debugging is easy.
  • Since it's structured using true/false statements, we can develop the programs quickly using logic programming.
  • As it's based on thinking, expression and implementation, it can be applied in non-computational programs too.
  • It supports special forms of knowledge such as meta-level or higher-order knowledge as it can be altered.

2.2 Functional programming paradigm

The functional programming paradigm has been in the limelight for a while now because of JavaScript, a functional programming language that has gained more popularity recently.

The functional programming paradigm has its roots in mathematics and it is language independent. The key principle of this paradigm is the execution of a series of mathematical functions.

You compose your program of short functions. All code is within a function. All variables are scoped to the function.

In the functional programming paradigm, the functions do not modify any values outside the scope of that function and the functions themselves are not affected by any values outside their scope.

To illustrate, let's identify whether the given number is prime or not in the functional programming paradigm.

Example in JavaScript:

function isPrime(number){ for(let i=2; i<=Math.floor(Math.sqrt(number)); i++){ if(number % i == 0 ){ return false; } } return true; } isPrime(15); //returns false

In the above example, we've used Math.floor() and Math.sqrt() mathematical functions to solve our problem efficiently. We can solve this problem without using built-in JavaScript mathematical functions, but to run the code efficiently it is recommended to use built-in JS functions.

number is scoped to the function isPrime() and it will not be affected by any values outside its scope. isPrime() function always produces the same output when given the same input.

NOTE: there are no for and while loops in functional programming. Instead, functional programming languages rely on recursion for iteration (Bhadwal, 2019).

Languages that support functional programming paradigm:

  • Haskell
  • OCaml
  • Scala
  • Clojure
  • Racket
  • JavaScript

Functional programming paradigm is often best used when:

  • Working with mathematical computations.
  • Working with applications aimed at concurrency or parallelism.

Why should you consider learning the functional programming paradigm?

  • Functions can be coded quickly and easily.
  • General-purpose functions can be reusable which leads to rapid software development.
  • Unit testing is easier.
  • Debugging is easier.
  • Overall application is less complex since functions are pretty straightforward.

2.3 Database processing approach

This programming methodology is based on data and its movement. Program statements are defined by data rather than hard-coding a series of steps.

A database is an organized collection of structured information, or data, typically stored electronically in a computer system. A database is usually controlled by a database management system (DBMS) ("What is a Database", Oracle, 2019).

To process the data and querying them, databases use tables. Data can then be easily accessed, managed, modified, updated, controlled and organized.

A good database processing approach is crucial to any company or organization. This is because the database stores all the pertinent details about the company such as employee records, transaction records and salary details.

Most databases use Structured Query Language (SQL) for writing and querying data.

Here’s an example in database processing approach (SQL):

CREATE DATABASE personalDetails; CREATE TABLE Persons ( PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) );

The PersonID column is of type int and will hold an integer. The LastName, FirstName, Address, and City columns are of type varchar and will hold characters, and the maximum length for these fields is 255 characters.

The empty Persons table will now look like this:

Database processing approach is often best used when:

  • Working with databases to structure them.
  • Accessing, modifying, updating data on the database.
  • Communicating with servers.

Why are databases important and why should you consider learning database processing approach?

  • Massive amount of data is handled by the database: Unlike spreadsheet or other tools, databases are used to store large amount of data daily.
  • Accurate: With the help of built-in functionalities in a database, we can easily validate.
  • Easy to update data: Data Manipulation Languages (DML) such as SQL are used to update data in a database easily.
  • Data integrity: With the help of built-in validity checks, we can ensure the consistency of data.

Conclusion

Programming paradigms reduce the complexity of programs. Every programmer must follow a paradigm approach when implementing their code. Each one has its advantages and disadvantages.

If you're a beginner, I would like to suggest learning object-oriented programming and functional programming first. Understand their concepts and try to apply them in your projects.

For example, if you're learning object-oriented programming, the pillars of object-oriented programming are Encapsulation, Abstraction, Inheritance and Polymorphism. Learn them by doing it. It will help you to understand their concepts on a deeper level, and your code will be less complex and more efficient and effective.

I strongly encourage you to read more related articles on programming paradigms. I hope this article helped you.

Please feel free to let me know if you have any questions.

You can contact and connect with me on Twitter @ThanoshanMV.

Thank you for reading.

Happy Coding!

References

  • Akhil Bhadwal. (2019). Funktsionaalne programmeerimine: mõisted, eelised, puudused ja rakendused
  • Alena Holligan. (2016). Millal kasutada OOP-d protseduurilise kodeerimise asemel
  • Saylori fond. (nd). Objektorienteeritud programmeerimise (OOP) eelised ja puudused
  • Mis on andmebaas | Oracle. (2019).