Why is object-oriented programming preferred in most projects? OOP offers an effective way to combat their complexity. Instead of considering the program as a sequence of executable instructions, it presents it as a group of objects with certain properties and performs certain actions with them. This leads to clearer, more reliable and easy to maintain applications.
The basic principles of object-oriented programming (OOP) were formed because limitations were discovered in the previously existing approaches. Among them - unlimited access to data and a large number of relationships that impose restrictions on making changes. Their awareness and reasons are important in order to understand what OOP is in programming and what are its advantages.
Procedural Languages
C, Pascal, FORTRAN and similar languages are procedural. That is, each of their operators orders the computer to do something: get the data, add the numbers, divide by six, display the result. The application in the procedural language is a list of instructions. If it is small, no other organizational principle (often called a paradigm) is required. The programmer creates a list of instructions, and the computer executes them.
Division into functions
When applications grow larger, the list is cumbersome. Few can understand more than a few hundred instructions until they are grouped. For this reason, the function has become a way to make applications more understandable to its creators. In some languages, the same concept may be called a subprogram or procedure.
The application is divided into functions, each of which has a clearly defined purpose and interface.
The idea of dividing into procedures can be expanded by grouping them into a larger object called a module, but the principle is similar: grouping components that execute lists of instructions.
The division into functions and modules is one of the cornerstones of structural programming, which for several decades before the emergence of OOP was the dominant paradigm.
Structural Programming Issues
As applications grew larger, structural programming began to experience difficulties. Projects were getting too complicated. Charts moved. Involved a greater number of programmers. Difficulty grew. Costs took off, the schedule moved on, and collapse came.
An analysis of the causes of these failures revealed flaws in the procedural paradigm. No matter how well a structured programming approach is implemented, large applications become overly complex.
What are the causes of these procedural language problems? First, functions have unlimited access to global data. Secondly, unrelated procedures and meanings poorly model the real world.
If we consider these problems in the context of a stock accounting program, then one of the most important global data elements is the totality of accounting units. Different functions can access them to enter a new value, display it, change it, etc.
Unlimited access
In a program written, for example, in C, there are two kinds of data. Local ones are hidden inside the function and are not used by other procedures.
When two or more functions must access the same data, the latter must be global. Such, for example, are information about counted subjects. Global data can be accessed by any procedure.
A large program has many functions and many global elements. The problem with the procedural paradigm is that it leads to even more potential links between them.
Such a large number of compounds causes several difficulties. Firstly, it complicates the understanding of the structure of the program. Secondly, making changes difficult. A change in a global data element may require adjustment of all functions that have access to it.
For example, in the accounting program, someone will decide that the code of the item to be taken into account should not consist of 5 digits, but of 12. This will require changing the data type from short to long. Code related functions should now be changed to work with the new format.
When elements change in a large application, it is difficult to say which procedures have access to them. But even if you find out, changing them can lead to incorrect operation with other global data. Everything is connected with everything else, so a change in one place comes around in another.
Real world modeling
The second and more important problem of the procedural paradigm is that its location of individual data and functions poorly models things in the real world. Here we are dealing with objects such as people and cars. They are neither like data nor functions. Complex real objects have attributes and behavior.
Attributes
Examples of attributes (sometimes called characteristics) for people are eye color and job title, for cars, power and number of doors. As it turned out, attributes in the real world are equivalent to data in the program. They have specific meanings, such as blue (eye color) or four (number of doors).
Behavior
Behavior is what real-world objects produce in response to some kind of impact. If you ask your boss for a raise, the answer is yes or no. If you press the brake, the car will stop. Saying and stopping are examples of behavior. Behavior is like a procedure: it is called to do something, and it does it. Thus, data and functions alone do not model real-world objects effectively.
Solution
An object in OOP is represented as a combination of data and functions. Only procedures that are called member functions in C ++ can get its values. Data is hidden and protected from change. Values and functions are encapsulated as a whole. Encapsulation and hiding are the main terms in the description of OO languages.
If you need to change the data, it is known exactly what functions interact with them. No other procedures can access them. This makes writing, debugging, and maintaining a program easier.
An application typically consists of several objects that interact with each other, calling member functions.
Today, the most widely used OOP language (object-oriented programming) is C ++ (plus-plus). Java lacks some features, such as pointers, patterns, and multiple inheritance, which makes it less powerful and versatile than C ++. C # has not yet reached the popularity of C ++.
It should be noted that the so-called member functions in C ++ are called methods in some other OO languages, such as Smalltalk. Data elements are called attributes. Calling an object's method is sending a message to it.
Analogy
You can imagine the objects of the departments of the company. In most organizations, employees do not work one day with staff, the next accruing salaries, and then doing retail for a week. Each department has its own staff with clearly assigned responsibilities. There is also our own data: salary, sales, employee records, etc. People in departments work with their information. The separation of the company, thus, facilitates control over its activities and maintains data integrity. Accounting is responsible for payroll. If you need to know the total amount of wages paid in the southern branch in July, you do not need to rummage through the archive. It is enough to send a note to the responsible person, wait until this person gets access to the data and sends a response with the required information. This ensures compliance with the regulations and the absence of outside interference. In the same way, an object in OOP provides the organization of an application.
It should be remembered that orientation to objects does not concern the details of the program. Most C ++ instructions correspond to operators of procedural languages such as C. Indeed, member functions in C ++ are very similar to functions in C. Only a wider context will allow us to establish whether the instruction is procedural or object-oriented.
Object in OOP: Definition
When considering the programming problem in the OO language, instead of questions about its division into separate functions, the problem of separation into objects arises. OOP thinking makes application development a lot easier. This occurs as a result of the similarity of software and real objects.
What things become objects in OOP? Typical categories are listed below.
A physical object in OOP is:
- transport in flow patterns;
- electrical elements in circuitry programs;
- countries in the economic model;
- aircraft in an air traffic control system.
Elements of the user's computer environment:
- menu;
- window;
- graphics (line, rectangle, circle);
- keyboard, mouse, printer, disk drives.
People:
- employees;
- students
- customers
- sellers.
Data:
- Ledger;
- private bussiness;
- vocabulary;
- table of latitudes and longitudes of settlements.
The connection between real-world objects and OOP was the result of a combination of functions and data: they revolutionized programming. There is no such close correspondence in procedural languages.
Class
Objects in OOP are members of classes. What does it mean? Programming languages have built-in data types. The int type, i.e., an integer, is predefined in C ++. You can declare as many int variables as you like.
Similarly, many objects of the same class are defined. It defines the functions and data included in its objects without creating them, just as int does not create variables.
A class in OOP is a description of a number of similar objects. Prince, Sting and Madonna are singers. There is not a single person with that name, but people can be so called if they have the appropriate characteristics. An OOP object is an instance of a class.
Inheritance
In life, classes are divided into subclasses. For example, animals are divided into amphibians, mammals, birds, insects, etc.
The principle of this kind of division is that each subclass has common characteristics with the class from which it comes. All cars have wheels and an engine. These are the defining characteristics of vehicles. In addition to the general characteristics, each subclass has its own characteristics. Buses have many seats, and trucks have space for carrying heavy loads.
Similarly, a base class can become the parent of several derived subclasses that can be defined so that they share its characteristics with the addition of its own. Inheritance is like a function that simplifies a procedural program. If several pieces of code do pretty much the same thing, you can extract common elements and put them in one procedure. Three sections of the application can call a function to perform common actions, but they can perform their own operations. Similarly, the base class contains data common to a group of derivatives. Like functions, inheritance reduces the OO program and clarifies the relationship of its elements.
Reuse
After the class is created and debugged, it can be transferred to other programmers for reuse in their own applications. This is similar to a function library that can go into different applications.
In OOP, inheritance is an extension of the idea of reuse. From an existing class, without changing it, you can form a new one with the addition of other functions. Ease of reusing existing software is an important advantage of OOP. It is believed that this provides a return on initial investment.
Creating New Data Types
Objects are useful for creating new data types. Suppose the program uses two-dimensional values (for example, coordinates or latitude and longitude), and there is a desire to express arithmetic operations with them:
position1 = position + origin,
where position1, position and origin are pairs of independent numerical values. Creating a class that includes these two values, and declaring the variables its objects creates a new data type.
Polymorphism Overload
The operators = (equal) and + (plus) used in positional arithmetic above do not work the same as with built-in types such as int. The position and other objects are not predefined, but are set programmatically. How do these operators know how to handle them? The answer is that for them you can set new patterns of behavior. These operations will be member functions of the Position class.
Using operators or procedures depending on what they are working with is called polymorphism. When an existing operator, such as + or =, gets the opportunity to work with a new data type, they say that it is overloaded. Congestion in OOP is a type of polymorphism. She is his important feature.
The book on OOP "Object-oriented programming for dummies" will allow everyone to get acquainted with this topic in more detail.