📜 ⬆️ ⬇️

Polymorphism, schmolimorphism ...

I think everyone has already completely confused endless articles about polymorphism, but they got me too, and I decided ... to write my own.

First of all, the basic principle (which the writers of all previous articles forget about completely): KISS . For some reason, to explain the basic concepts it is considered necessary to involve two or three programming languages ​​(usually unknown to the reader), a couple of two-page examples, etc.

This is a good way if you want to show your steepness in an interview - sometimes they can even positively evaluate it. Although I personally would hardly have put a high mark on such a candidate. For it simply means that either a person is engaged in self-admiration (not a very good option), or he really does not know how to express his thoughts (even worse option).
')
Basic concepts need to be able to explain without the use of programming languages ​​in general! The second stage is to show how the basic concepts are used in one or another programming language. But that's another story.

So. Let's try to tell a person to a programmer who does not know a single programming language known to you (well, for example, he used FORTRAN-66 all his life) about polymorphism.

Start over. With objects. What is an object in OOP? This is an abstraction that allows you to describe large programs. We group the data and processing code of this data into some entity called “object”. Why do we do this? Well ... so the program seemed looking simpler. It is human nature to anthropomorphize everything (do not believe it - watch cartoons) and it seems to him that a program made up of such small “little men” will be clearer than a million unrelated formulas. Of course, when we write programs, we do not model a person in sufficient detail: if our little man is called on to monitor the state of a printer or a bank account, then we, in general, do not care what color his eyes are and do not even care what gender this imaginary man is. We give it only the most rudimentary memory (say, a little man, a serving printer can remember how many pages were printed on this printer, and a little man serving a bank account will remember how much money on this account) and worry only about a couple of elementary operations (say, “printer man” can print text on paper - or return an error if the printer runs out of paper, and the “accounting” man can withdraw money from the account - or return an error if they are not there).

Fine. Now we know what an object is (we know the concept, but not its implementation in any programming language - although I am sure that a person who has worked for 40 years with FORTRAN66 will give you a dozen ways to implement this concept). Let's go further. Of course, our little man will fight for his workplace and “climb into his desk” and change the amount of money in the account will be offended and either refuse to do it, or hadrit and work poorly afterwards. This principle is called “encapsulation”: for every man’s own state, he is responsible for himself. Sometimes it is useful to break this principle: let's say the auditor (in programming commonly called the inspector) it is useful to provide exclusive rights to do his job, but if he misuses them (say, removes all the money from the account and runs away), then the whole program may collapse.

Farther. Polymorphism. Inheritance is usually considered the second guiding principle of OOP, but in reality polymorphism is a much simpler thing. This principle simply states that the resume of the employee does not coincide with the employee himself. Let's say if a writer hires a person who will write down his brilliant thoughts - then he doesn’t care how exactly the “clerk” will do it: shorthand on paper, using a typewriter or carving text on a stone. The main thing that he did it quickly enough. Of course, this may be of interest to a company with which the writer has a contract (that is, a programmer who is writing a program) because a piece of paper is cheaper than a processed stone. But that's another story. There are languages ​​with a static implementation when the resume and the list of skills of the employee must exist explicitly and their compliance is checked even before the factory is built and dynamic languages ​​- there the formal concept of "resume" can be omitted! Although usually a programmer writing a program, some resumes on sheets of paper are still formed.

Wonderful. What is inheritance? Well, here, too, there are no secrets: it is not always convenient to prepare yourself an employee “from kindergarten” (that is, to write a class / prototype / etc from scratch). Sometimes it is easier to take a ready-made employee and finish him a little. Let's say if our genius writer needs a person who can not only record ingenious thoughts, but also sketch out the designs of locks in which the action takes place, then it may be better to take some clerk and teach him to draw these locks. True there may be surprises. It turns out that the clerk has some kind of "cockroaches in his head." Well, for example, at the command “take a pen in your hands and prepare for a letter,” he also takes a blank sheet of paper and lined it - and on the plans of locks such rulers are undesirable. The more cycles of retraining (the “higher” the inheritance tree), the greater the chances for the appearance of strange overlays. Ideally, it would be good to use only “specially trained workers” who are selected by resume - but this can be very expensive. Teaching a turner to wipe the parts with a special solution can be much easier than creating a new specialist who can sharpen parts and wipe them with a cloth.

For a snack. What is an abstract class? This is a class (class in the school sense - a place where people are taught something), which produces semi-finished products. Not specialists, but unskilled specialists. He studied, studied, but learned only to turn the machine on and off. But to handle the details (sharpen them or mill) - he still does not know how. Most programming languages ​​(of course, only those where there are formal summaries) allow us to describe only the “classes for training” of such specialists. It is impossible to release a nonspecialist, but you can add another class to the “young fighter training school” and release a turner. Or another - in order to prepare a milling machine. Well, the abstract function is the same function that the class does not teach. But he can already explain to a specialist what to do after he learns this function - say, without having trained him in handling parts, he can explain how to handle a box of parts: take the first part from the input tray, process it (you will learn later), put it in the tray processed piece, poktorit until exhaustion of the input tray ... All warnings about the retraining of specialists remain in force: if the classes are poorly coordinated among themselves ... well, you went to school, right?

Still want. Well, let's. About virtual functions. What are virtual functions? Well, these are just functions of objects. In fact, virtual functions do not have any features. Features do not have virtual functions. This is an attempt to “speed everything up and improve”, leading to problems. Indeed: men look good on paper, but the program runs on a computer! And he is pretty dumb. Performs about ten elementary operations (addition, subtraction, etc), and the rest should be taught. What does this mean for our approach? This means that if we need to ask the “machine tool specialist” to turn off the machine, the computer needs to “look at his head”, understand how he turns off the machines and, in fact, do it. And if the operation of turning off the machine is very simple? We will spend more time searching for data in the head of a specialist! And often the operation of turning off the machine for all machines is the same. The last button on the left. There is a "brilliant" idea: let's see that we need to turn off the machine on which the specialist worked to make the extreme button on the left. This is how a non-virtual function works: it looks at a person’s resume - and decides what to do in a particular case. Everything will work. Moreover, if a tricky drilling machine appears with a shutdown button on the right, then everything will be fine if the foreman at the workshop will know that she is dealing with a drilling machine and a specialist working on it. But if the team to turn off the machines comes from the fire inspectorate, which does not know about such subtleties ... it will ask all specialists to turn off the machines, they will all press the leftmost button (remember - we decided "not to look to the specialist in the head" to speed up the program) including the person who manages the drilling machine ... crackle, noise, din, “the program has performed an unacceptable operation and will be closed” ...

Well, not a virtual destructor is just a non-virtual function that dismisses our specialist. It is clear that there is no function that so strongly influences the specialist God himself to be virtual, but ... what if he has no other non-virtual functions? Well, it will be necessary "in the head of a specialist" to organize a whole section with a list of functions and its processing - all for the sake of one function! Sometimes it seems overkill and if the object has no virtual functions, then its destructor is made non-virtual. Usually retraining such specialists is more expensive ...

That's about it. How to use these principles in practice and in a particular programming language is another question. In PHP programs, very much there are polymorphic classes for working with databases: different databases have their own problems (for example, to put in the database "Hello, world!" In quotes, you sometimes need to use insert ("" "Hello, World!" ")) and sometimes insert ("\" Hello, World \ ""), but 90% of the functionality is the same!

PS For those who want to laugh at the problems caused by the inheritance of a selection of jokes (tip Comrade. Stepanow ). Almost all problems are caused by “cockroaches in my head” from “incomplete retraining” when inheriting ...

Source: https://habr.com/ru/post/37640/


All Articles