Отвлеченная абстракция ошибка

From Wikipedia, the free encyclopedia

From Wikipedia, the free encyclopedia

Reification (also known as concretism, hypostatization, or the fallacy of misplaced concreteness) is a fallacy of ambiguity, when an abstraction (abstract belief or hypothetical construct) is treated as if it were a concrete real event or physical entity.[1][2]
In other words, it is the error of treating something that is not concrete, such as an idea, as a concrete thing. A common case of reification is the confusion of a model with reality: «the map is not the territory».

Reification is part of normal usage of natural language (just like metonymy for instance), as well as of literature, where a reified abstraction is intended as a figure of speech, and actually understood as such. But the use of reification in logical reasoning or rhetoric is misleading and usually regarded as a fallacy.[3]

Etymology[edit]

From Latin res («thing») and —fication, a suffix related to facere («to make»).[4] Thus reification can be loosely translated as «thing-making»; the turning of something abstract into a concrete thing or object.

Theory[edit]

Reification takes place when natural or social processes are misunderstood or simplified; for example, when human creations are described as «facts of nature, results of cosmic laws, or manifestations of divine will».[5]

Reification may derive from an inborn tendency to simplify experience by assuming constancy as much as possible.[6]

Fallacy of misplaced concreteness[edit]

According to Alfred North Whitehead, one commits the fallacy of misplaced concreteness when one mistakes an abstract belief, opinion, or concept about the way things are for a physical or «concrete» reality: «There is an error; but it is merely the accidental error of mistaking the abstract for the concrete. It is an example of what might be called the ‘Fallacy of Misplaced Concreteness.«[7] Whitehead proposed the fallacy in a discussion of the relation of spatial and temporal location of objects. He rejects the notion that a concrete physical object in the universe can be ascribed a simple spatial or temporal extension, that is, without reference to its relations to other spatial or temporal extensions.

[…] apart from any essential reference of the relations of [a] bit of matter to other regions of space […] there is no element whatever which possesses this character of simple location. [… Instead,] I hold that by a process of constructive abstraction we can arrive at abstractions which are the simply located bits of material, and at other abstractions which are the minds included in the scientific scheme. Accordingly, the real error is an example of what I have termed: The Fallacy of Misplaced Concreteness.[8]

Vicious abstractionism[edit]

William James used the notion of «vicious abstractionism» and «vicious intellectualism» in various places, especially to criticize Immanuel Kant’s and Georg Wilhelm Friedrich Hegel’s idealistic philosophies. In The Meaning of Truth, James wrote:

Let me give the name of «vicious abstractionism» to a way of using concepts which may be thus described: We conceive a concrete situation by singling out some salient or important feature in it, and classing it under that; then, instead of adding to its previous characters all the positive consequences which the new way of conceiving it may bring, we proceed to use our concept privatively; reducing the originally rich phenomenon to the naked suggestions of that name abstractly taken, treating it as a case of «nothing but» that concept, and acting as if all the other characters from out of which the concept is abstracted were expunged. Abstraction, functioning in this way, becomes a means of arrest far more than a means of advance in thought. … The viciously privative employment of abstract characters and class names is, I am persuaded, one of the great original sins of the rationalistic mind.[9]

In a chapter on «The Methods and Snares of Psychology» in The Principles of Psychology, James describes a related fallacy, the psychologist’s fallacy, thus: «The great snare of the psychologist is the confusion of his own standpoint with that of the mental fact about which he is making his report. I shall hereafter call this the «psychologist’s fallacy» par excellence» (volume 1, p. 196). John Dewey followed James in describing a variety of fallacies, including «the philosophic fallacy», «the analytic fallacy», and «the fallacy of definition».[10]

Use of constructs in science[edit]

The concept of a «construct» has a long history in science; it is used in many, if not most, areas of science. A construct is a hypothetical explanatory variable that is not directly observable. For example, the concepts of motivation in psychology, utility in economics, and gravitational field in physics are constructs; they are not directly observable, but instead are tools to describe natural phenomena.

The degree to which a construct is useful and accepted as part of the current paradigm in a scientific community depends on empirical research that has demonstrated that a scientific construct has construct validity (especially, predictive validity).[11] Thus, in contrast to Whitehead, many psychologists seem to believe that, if properly understood and empirically corroborated, the «reification fallacy» applied to scientific constructs is not a fallacy at all; it is one part of theory creation and evaluation in ‘Normal science’.

Stephen Jay Gould draws heavily on the idea of fallacy of reification in his book The Mismeasure of Man. He argues that the error in using intelligence quotient scores to judge people’s intelligence is that, just because a quantity called «intelligence» or «intelligence quotient» is defined as a measurable thing does not mean that intelligence is real; thus denying the validity of the construct «intelligence.»[12]

Relation to other fallacies[edit]

Pathetic fallacy (also known as anthropomorphic fallacy or anthropomorphization) is a specific type[dubious – discuss] of reification. Just as reification is the attribution of concrete characteristics to an abstract idea, a pathetic fallacy is committed when those characteristics are specifically human characteristics, especially thoughts or feelings.[13] Pathetic fallacy is also related to personification, which is a direct and explicit ascription of life and sentience to the thing in question, whereas the pathetic fallacy is much broader and more allusive.

The animistic fallacy involves attributing personal intention to an event or situation.

Reification fallacy should not be confused with other fallacies of ambiguity:

  • Accentus, where the ambiguity arises from the emphasis (accent) placed on a word or phrase
  • Amphiboly, a verbal fallacy arising from ambiguity in the grammatical structure of a sentence
  • Composition, when one assumes that a whole has a property solely because its various parts have that property
  • Division, when one assumes that various parts have a property solely because the whole has that same property
  • Equivocation, the misleading use of a word with more than one meaning

As a rhetorical device[edit]

The rhetorical devices of metaphor and personification express a form of reification, but short of a fallacy. These devices, by definition, do not apply literally and thus exclude any fallacious conclusion that the formal reification is real. For example, the metaphor known as the pathetic fallacy, «the sea was angry» reifies anger, but does not imply that anger is a concrete substance, or that water is sentient. The distinction is that a fallacy inhabits faulty reasoning, and not the mere illustration or poetry of rhetoric.[2]

Counterexamples[edit]

Reification, while usually fallacious, is sometimes considered a valid argument. Thomas Schelling, a game theorist during the Cold War, argued that for many purposes an abstraction shared between disparate people caused itself to become real. Some examples include the effect of round numbers in stock prices, the importance placed on the Dow Jones Industrial index, national borders, preferred numbers, and many others.[14]

See also[edit]

  • All models are wrong
  • Counterfactual definiteness
  • Idolatry
  • Objectification
  • Philosophical realism
  • Surrogation
  • Hypostatic abstraction

References[edit]

  1. ^ Reification, Encyclopædia Britannica
  2. ^ a b «Logical Fallacies, Formal and Informal». usabig.com. Archived from the original on 22 November 2011. Retrieved 10 April 2018.
  3. ^ Dowden, Bradley. «Fallacy». Internet Encyclopedia of Philosophy. ISSN 2161-0002. Retrieved 26 April 2021. Whether a phrase commits the fallacy depends crucially upon whether the use of the inaccurate phrase is inappropriate in the situation. In a poem, it is appropriate and very common to reify nature, hope, fear, forgetfulness, and so forth, that is, to treat them as if they were objects or beings with intentions. In any scientific claim, it is inappropriate.
  4. ^ «reification, n.» OED Online. Oxford University Press, September 2016. Web. 24 September 2016.
    Format
  5. ^ David K. Naugle (2002). Worldview: the history of a concept. Wm. B. Eerdmans Publishing. p. 178. ISBN 978-0-8028-4761-4.
  6. ^ David Galin in B. Alan Wallace, editor, Buddhism & Science: Breaking New Ground. Columbia University Press, 2003, p. 132.
  7. ^ Whitehead, Alfred North (1997) [1925]. Science and the Modern World. Free Press (Simon & Schuster). p. 52. ISBN 978-0-684-83639-3.
  8. ^ Whitehead, Alfred North (1997) [1925]. Science and the Modern World. Free Press (Simon & Schuster). p. 58. ISBN 978-0-684-83639-3.
  9. ^ James, William, The Meaning of Truth, A Sequel to ‘Pragmatism, (1909/1979), Harvard University Press, pp. 135-136
  10. ^ Winther, Rasmus G. (2014). James and Dewey on Abstraction. The Pluralist 9 (2), pp. 9-17 http://philpapers.org/archive/WINJAD.pdf
  11. ^ Kaplan, R. M., & Saccuzzo, D. P. (1997). Psychological Testing. Chapter 5. Pacific Grove: Brooks-Cole.
  12. ^ Pitkin, Hanna Fenichel (March 1987). «Rethinking reification». Theory and Society. 16 (2): 263–293. doi:10.1007/bf00135697. ISSN 0304-2421. S2CID 189890548.
  13. ^ http://www.britannica.com/EBchecked/topic/446415/pathetic-fallacy pathetic fallacy. Retrieved on: 9 October 2012
  14. ^ Schelling, Thomas C. (1980). The Strategy of Conflict. Harvard University Press. ISBN 9780674840317.

From Wikipedia, the free encyclopedia

Reification (also known as concretism, hypostatization, or the fallacy of misplaced concreteness) is a fallacy of ambiguity, when an abstraction (abstract belief or hypothetical construct) is treated as if it were a concrete real event or physical entity.[1][2]
In other words, it is the error of treating something that is not concrete, such as an idea, as a concrete thing. A common case of reification is the confusion of a model with reality: «the map is not the territory».

Reification is part of normal usage of natural language (just like metonymy for instance), as well as of literature, where a reified abstraction is intended as a figure of speech, and actually understood as such. But the use of reification in logical reasoning or rhetoric is misleading and usually regarded as a fallacy.[3]

Etymology[edit]

From Latin res («thing») and —fication, a suffix related to facere («to make»).[4] Thus reification can be loosely translated as «thing-making»; the turning of something abstract into a concrete thing or object.

Theory[edit]

Reification takes place when natural or social processes are misunderstood or simplified; for example, when human creations are described as «facts of nature, results of cosmic laws, or manifestations of divine will».[5]

Reification may derive from an inborn tendency to simplify experience by assuming constancy as much as possible.[6]

Fallacy of misplaced concreteness[edit]

According to Alfred North Whitehead, one commits the fallacy of misplaced concreteness when one mistakes an abstract belief, opinion, or concept about the way things are for a physical or «concrete» reality: «There is an error; but it is merely the accidental error of mistaking the abstract for the concrete. It is an example of what might be called the ‘Fallacy of Misplaced Concreteness.«[7] Whitehead proposed the fallacy in a discussion of the relation of spatial and temporal location of objects. He rejects the notion that a concrete physical object in the universe can be ascribed a simple spatial or temporal extension, that is, without reference to its relations to other spatial or temporal extensions.

[…] apart from any essential reference of the relations of [a] bit of matter to other regions of space […] there is no element whatever which possesses this character of simple location. [… Instead,] I hold that by a process of constructive abstraction we can arrive at abstractions which are the simply located bits of material, and at other abstractions which are the minds included in the scientific scheme. Accordingly, the real error is an example of what I have termed: The Fallacy of Misplaced Concreteness.[8]

Vicious abstractionism[edit]

William James used the notion of «vicious abstractionism» and «vicious intellectualism» in various places, especially to criticize Immanuel Kant’s and Georg Wilhelm Friedrich Hegel’s idealistic philosophies. In The Meaning of Truth, James wrote:

Let me give the name of «vicious abstractionism» to a way of using concepts which may be thus described: We conceive a concrete situation by singling out some salient or important feature in it, and classing it under that; then, instead of adding to its previous characters all the positive consequences which the new way of conceiving it may bring, we proceed to use our concept privatively; reducing the originally rich phenomenon to the naked suggestions of that name abstractly taken, treating it as a case of «nothing but» that concept, and acting as if all the other characters from out of which the concept is abstracted were expunged. Abstraction, functioning in this way, becomes a means of arrest far more than a means of advance in thought. … The viciously privative employment of abstract characters and class names is, I am persuaded, one of the great original sins of the rationalistic mind.[9]

In a chapter on «The Methods and Snares of Psychology» in The Principles of Psychology, James describes a related fallacy, the psychologist’s fallacy, thus: «The great snare of the psychologist is the confusion of his own standpoint with that of the mental fact about which he is making his report. I shall hereafter call this the «psychologist’s fallacy» par excellence» (volume 1, p. 196). John Dewey followed James in describing a variety of fallacies, including «the philosophic fallacy», «the analytic fallacy», and «the fallacy of definition».[10]

Use of constructs in science[edit]

The concept of a «construct» has a long history in science; it is used in many, if not most, areas of science. A construct is a hypothetical explanatory variable that is not directly observable. For example, the concepts of motivation in psychology, utility in economics, and gravitational field in physics are constructs; they are not directly observable, but instead are tools to describe natural phenomena.

The degree to which a construct is useful and accepted as part of the current paradigm in a scientific community depends on empirical research that has demonstrated that a scientific construct has construct validity (especially, predictive validity).[11] Thus, in contrast to Whitehead, many psychologists seem to believe that, if properly understood and empirically corroborated, the «reification fallacy» applied to scientific constructs is not a fallacy at all; it is one part of theory creation and evaluation in ‘Normal science’.

Stephen Jay Gould draws heavily on the idea of fallacy of reification in his book The Mismeasure of Man. He argues that the error in using intelligence quotient scores to judge people’s intelligence is that, just because a quantity called «intelligence» or «intelligence quotient» is defined as a measurable thing does not mean that intelligence is real; thus denying the validity of the construct «intelligence.»[12]

Relation to other fallacies[edit]

Pathetic fallacy (also known as anthropomorphic fallacy or anthropomorphization) is a specific type[dubious – discuss] of reification. Just as reification is the attribution of concrete characteristics to an abstract idea, a pathetic fallacy is committed when those characteristics are specifically human characteristics, especially thoughts or feelings.[13] Pathetic fallacy is also related to personification, which is a direct and explicit ascription of life and sentience to the thing in question, whereas the pathetic fallacy is much broader and more allusive.

The animistic fallacy involves attributing personal intention to an event or situation.

Reification fallacy should not be confused with other fallacies of ambiguity:

  • Accentus, where the ambiguity arises from the emphasis (accent) placed on a word or phrase
  • Amphiboly, a verbal fallacy arising from ambiguity in the grammatical structure of a sentence
  • Composition, when one assumes that a whole has a property solely because its various parts have that property
  • Division, when one assumes that various parts have a property solely because the whole has that same property
  • Equivocation, the misleading use of a word with more than one meaning

As a rhetorical device[edit]

The rhetorical devices of metaphor and personification express a form of reification, but short of a fallacy. These devices, by definition, do not apply literally and thus exclude any fallacious conclusion that the formal reification is real. For example, the metaphor known as the pathetic fallacy, «the sea was angry» reifies anger, but does not imply that anger is a concrete substance, or that water is sentient. The distinction is that a fallacy inhabits faulty reasoning, and not the mere illustration or poetry of rhetoric.[2]

Counterexamples[edit]

Reification, while usually fallacious, is sometimes considered a valid argument. Thomas Schelling, a game theorist during the Cold War, argued that for many purposes an abstraction shared between disparate people caused itself to become real. Some examples include the effect of round numbers in stock prices, the importance placed on the Dow Jones Industrial index, national borders, preferred numbers, and many others.[14]

See also[edit]

  • All models are wrong
  • Counterfactual definiteness
  • Idolatry
  • Objectification
  • Philosophical realism
  • Surrogation
  • Hypostatic abstraction

References[edit]

  1. ^ Reification, Encyclopædia Britannica
  2. ^ a b «Logical Fallacies, Formal and Informal». usabig.com. Archived from the original on 22 November 2011. Retrieved 10 April 2018.
  3. ^ Dowden, Bradley. «Fallacy». Internet Encyclopedia of Philosophy. ISSN 2161-0002. Retrieved 26 April 2021. Whether a phrase commits the fallacy depends crucially upon whether the use of the inaccurate phrase is inappropriate in the situation. In a poem, it is appropriate and very common to reify nature, hope, fear, forgetfulness, and so forth, that is, to treat them as if they were objects or beings with intentions. In any scientific claim, it is inappropriate.
  4. ^ «reification, n.» OED Online. Oxford University Press, September 2016. Web. 24 September 2016.
    Format
  5. ^ David K. Naugle (2002). Worldview: the history of a concept. Wm. B. Eerdmans Publishing. p. 178. ISBN 978-0-8028-4761-4.
  6. ^ David Galin in B. Alan Wallace, editor, Buddhism & Science: Breaking New Ground. Columbia University Press, 2003, p. 132.
  7. ^ Whitehead, Alfred North (1997) [1925]. Science and the Modern World. Free Press (Simon & Schuster). p. 52. ISBN 978-0-684-83639-3.
  8. ^ Whitehead, Alfred North (1997) [1925]. Science and the Modern World. Free Press (Simon & Schuster). p. 58. ISBN 978-0-684-83639-3.
  9. ^ James, William, The Meaning of Truth, A Sequel to ‘Pragmatism, (1909/1979), Harvard University Press, pp. 135-136
  10. ^ Winther, Rasmus G. (2014). James and Dewey on Abstraction. The Pluralist 9 (2), pp. 9-17 http://philpapers.org/archive/WINJAD.pdf
  11. ^ Kaplan, R. M., & Saccuzzo, D. P. (1997). Psychological Testing. Chapter 5. Pacific Grove: Brooks-Cole.
  12. ^ Pitkin, Hanna Fenichel (March 1987). «Rethinking reification». Theory and Society. 16 (2): 263–293. doi:10.1007/bf00135697. ISSN 0304-2421. S2CID 189890548.
  13. ^ http://www.britannica.com/EBchecked/topic/446415/pathetic-fallacy pathetic fallacy. Retrieved on: 9 October 2012
  14. ^ Schelling, Thomas C. (1980). The Strategy of Conflict. Harvard University Press. ISBN 9780674840317.

Причуды абстракций

Время прочтения
10 мин

Просмотры 28K

image

За годы преподавания и коммерческой разработки я повстречал много студентов и разработчиков, которые не до конца понимают смысл слова абстракция. Из многочисленных попыток разъяснить смысл этого термина получилась настоящая статья. Что Вы найдете под катом:

  • Определение понятия абстракции и объяснение откуда оно взялось в ООП.
  • Объяснение на простых примерах, что такое барьер абстракции, побочный эффект абстракции.
  • Как получается хардкод.

Что такое абстракция?

Википедия определяет абстракцию и процесс абстрагирования следующим образом:
Абстра́кция (от лат. abstractio — отвлечение) — отвлечение в процессе познания от несущественных сторон, свойств, связей объекта (предмета или явления) с целью выделения их существенных, закономерных признаков; абстрагирование; теоретическое обобщение как результат такого отвлечения.

В европейской философии и логике абстрагирование трактуется как способ поэтапного продуцирования понятий, которые образуют всё более общие модели — иерархию абстракций. Наиболее развитой системой абстракций обладает математика. Степень отвлечённости обсуждаемого понятия называется уровнем абстракции. В зависимости от целей и задач, можно рассуждать об одном и том же объекте на разных уровнях абстракции.

Гради Буч определяет понятие абстракции значительно проще, но смысл тот же:
Абстракция выделяет существенные характеристики некоторого объекта, отличающие его от всех других объектов.

Зачем нужна абстракция?

Абстракции выполняют защитную функцию и помогают нам не сойти с ума от переизбытка информации. Представьте, как бы нам жилось, если при письме шариковой ручкой пришлось бы думать о том, что миллиарды молекул чернил взаимодействуют с молекулами бумаги, чтобы получилась буква. Другими словами, не тратя время на ненужные подробности, мы можем ухватить самую суть — взглянуть на проблему «сверху».

Если бы не фотография с высоты птичьего полета, можно ли было бы себе представить насколько правильно спроектирована Барселона? Кстати, про пример с шариковой ручкой, читать бы тоже не получилось — начертания одной и той же буквы на письме отличаются даже у одного человека.

Абстрактное мышление — это механизм, который позволяет нам перерабатывать и усваивать кучу новых сведений. Если бы не было абстракции, то единственный вариант для нас — это остаться очень примитивными существами.

В Бразилии живет племя небольшое племя индейцев Пираха. Представители этой народности обладают крайне скудным абстрактным мышлением. Их алфавит состоит из трех гласных и восьми согласных. У них нет слов, обозначающих цифры, вместо цифр у них два понятия — несколько и много. У них нет цветов — только понятия светлый и темный, времени и истории — они живут только сегодняшним днем и помнят только то. что помнит старейший из ныне живущих; нет — религии, ремесел, искусства. У них еще много чего нет в нашем привычном понимании. И это все потому, что не развито абстрактное мышление. Правда, справедливости ради, стоит отметить, что при этом они себя ощущают абсолютно счастливыми людьми!

Итак, абстрагирование нам нужно как способ познания и описания окружающего мира, для обмена информацией друг с другом. Абстракции позволяют провести декомпозицию предметной области на набор понятий и связей между ними.

На картинке изображен Legoland в Лондоне. Несмотря на то, что все предметы собраны из детского конструктора, мы без труда узнаем в них дома, окна, двери, городские кварталы, людей.

Барьеры и побочные эффекты абстракций

Чтобы понять ключевые свойства абстракций проведем аналогию с построением проекций на плоскость.

Предположим, что у нас есть три фигуры: шар, цилиндр и параллелепипед, при этом ось симметрии цилиндра, проходящая через центры окружностей в основании, параллельна какой-нибудь оси симметрии параллелепипеда. Очевидно, что можно выбрать две плоскости для построения проекций таким образом, что шар и цилиндр спроецируются в окружности, а цилиндр и параллелепипед — в прямоугольники.

Проекция в нашем примере иллюстрирует абстракцию объекта — геометрической фигуры. Что мы видим — на одной плоскости не отличишь проекции шара и цилиндра, а на другой — цилиндра и параллелепипеда. Этот эффект называется барьером абстракции. Абстракция представляет не весь объект целиком, а только лишь его существенный набор характеристик.Нужно быть готовым к тому, что некоторые очень непохожие друг на друга объекты, могут стать неразличимыми. Если это неудобно, то нужно выбирать другой набор абстракций.

С другой стороны, как мы видим из примера, цилиндр, может проецироваться и в окружность, и в прямоугольник — объекты с различными геометрическими свойствами, отличными от тех, что есть у цилиндра. Наличие у абстракции собственных свойств, отличных от свойств абстрагируемого объекта, называется побочным эффектом абстракции.

На самой первой картинке изображены две фигуры, собранные из щепок, так что при определенном освещении они отбрасывают «человеческие тени». Мне, например, кажется, что там один силуэт мужской, а другой — женский. Это тоже побочный эффект абстракций. Теперь мы можем классифицировать все фигуры по их тени.

Примеры абстракций

Сфера применения Абстракция Комментарий
Целые числа Число из кольца Zp, где p = 2^разрядность (8, 16, 32, 64 бита) Данная абстракция позволяет представить целые числа только из отрезка –p/2+1 до p/2. Побочный эффект – проблема переполнения.
Вещественные числа Числа с плавающей точкой Вещественных чисел несчетное число, а чисел с плавающей точкой — всего лишь конечное. Это значит, что несчетное количество вещественных чисел представлены одним числом с плавающей точкой. Побочный эффект – ошибка округления, из-за который два числа нельзя сравнивать с помощью операции сравнения, а лишь по модулю некоторого маленького epsilon |a-b| < epsilon => a == b, или a/b*1000 может сильно отличаться от a*1000/b. Появилась даже целая дисциплина в математике – численные методы, которая изучает как организовать вычисления с плавающей точкой так, чтобы результаты не сильно отличались от вычислений с вещественными числами.
Деньги Числа с плавающей точкой Погрешность округления чисел с плавающей точкой делает, если не невозможным их использование для финансовых операций, то, по крайней мере, сильно усложняет жизнь. В любом случае, я бы сначала подумал в сторону написания отдельного класса для денежных единиц.
Изображение Машинная графика Машинная графика развивается семимильными шагами, чтобы сделать изображение на экране компьютера все более реалистичным.
Программное обеспечение Процедура Процедура является базовым элементом декомпозиции в процедурном программировании. Побочный эффект — процедура жестко заданная последовательность команд, которую невозможно изменить без переписывания самой процедуры.
Программное обеспечение Класс О классах будем говорить ниже.
Предметная область Абстракция сущности и связи между сущностями Побочный эффект — отражает представление, заблуждения, предубеждения и т.д. о предметной области конкретного субъекта.
Бизнес-логика Процедура Как уже говорилось выше — побочный эффект процедуры — жесткая последовательность команд. Бизнес-логика же подвержена изменениям, как правило содержит много исключений, о которых пользователи обычно забывают рассказать. Попытка представить бизнес-операцию в виде процедуры часто делает терпит неудачу.
Программное обеспечение Поток для распараллеливания операций Многопоточное программирование получилось настолько сложным для восприятия, что немного людей в нем разбирается.
Квадрат — это прямоугольник, у которого все стороны равны. Класс квадрат нельзя наследовать от прямоугольника. Классы — это абстракции. У них есть свои собственные свойства, которые отличаются от математических объектов и которые делают невозможным наследование.

Классы

Гради Буч так определяет ООП:
Объектно-ориентированное программирование — это методология программирования, основанная на представлении программы в виде совокупности объектов, каждый из которых является экземпляром определенного класса, а классы образуют иерархию наследования.

В этом определении самый важный момент — это иерархия наследования. Потому что именно наследование отличает ООП от всех других методологий.

Два основных принципа человеческого мышления — это группировка и обобщение. Классы — это, по сути, абстракции механизмов группировки и обобщения человеческого мозга. Естественно, со своими побочными эффектами и барьером. При этом группировка достигается тем, что похожим объектам сопоставляется один класс, а обобщение в ООП достигается за счет иерархии классов. Иерархии классов реализуются через полиморфизм.

ООП, кстати, интересно еще хотя бы и тем, что это, пожалуй, последняя парадигма программирования на данный момент, которая поддерживается на аппаратном уровне.

Главный побочный эффект классов — они отражают опыт, стереотипы, предубеждения того программиста, который их написал. Отсюда следует, что разные люди получат разный набор классов для одной и той же задачи. Более того, один и тот же человек, решая одну и туже задачу, но в разные моменты времени, получит разный набор классов, просто потому что его жизненный опыт меняется.

Второй побочный эффект, который стоит отметить — чужой код всегда менее понятный, чем свой собственный.


Разберемся почему так происходит. Когда человек пишет код, для него естественнее двигаться снизу вверх — от более низкоуровневых компонент к более высокоуровневым. Сначала написали один класс, потом второй, который зависит от первого, затем третий, который зависти от первого и второго, четвертый — от третьего и т.д.

Когда же человек пытается понять чужой код, он как раз двигается наоборот — сверху вниз. То есть сначала понимает общую суть, затем разбивает на компоненты, потом пытается понять суть каждого компонента и т.д. Часто эти движения мысли снизу вверх и сверху вниз у разных людей не совпадают. Естественно, что изучающему чужой код было бы легче, если разбиение кода на компоненты совпадало с его собственными убеждениями, как надо делать. Если это не так, придется затрачивать определенные усилия, чтобы понять ход мыслей разработчика. Поэтому, когда кто-то говорит, что здесь «полный хардкод», но если я перепишу, то будет все проще и понятнее. Это всегда 100% правда… Но только для него, для остальных ценность переписывания уже не так очевидна.

Кстати, если ничего не предпринимать специально, то при разработке снизу вверх, код становится сильно связанным между собой, то есть не повторно используемым. Чтобы побороть этот эффект надо следовать принципу инверсии зависимостей (The Dependency Inversion Principle).

Проиллюстрируем как проявляется описанный побочный эффект на простом примере. Многие жители крупных городов закупаются в крупных супермаркетах. Предположим, что жена отправляет мужа за покупками и, чтобы он не забыл, как обычно, чего-нибудь, составляет список «для тех кто в танке».
Постараемся проследить ход ее мыслей:
— Так чего я сегодня буду готовить на ужин?
— Надо приготовить чего-нибудь вкусненькое, чтобы побаловать ребенка.
— Так, нужна будет мука, молоко.
— Кажется в миксере сели батарейки.
— Стоп! Ребенку нужны витамины. Морковь. Буду делать морковный сок. и мандарины. Скоро же Новый год!
— А хлеб дома есть? Нет, кажется, нет.Значит, надо купить!
— Еще надо купить масло.
— Забыла про ребенка — витамины. Купить яблоки.
— Чего-то ручка плохо пишет. Наверное скоро кончатся чернила. Надо купить!
— Так, ребенку надо купить сока.
— А еще игрушку — пусть порадуется.
— Картошка у нас есть на борщ? На борщ хватит, но на неделю нет. Значит тоже надо купить.
— Чуть не забыла учительница просила принести две тетради.
— К борщу нужна сметана.
— Вроде сахар кончился.
— Ребенок любит виноград.
— И еще надо купить бутилированной воды.

В итоге получаем следующий список:

  • мука
  • молоко
  • батарейки
  • морковь
  • мандарины
  • хлеб
  • масло
  • яблоки
  • ручка
  • сок
  • игрушка
  • картофель
  • тетради
  • сметана
  • сахар
  • виноград
  • вода

Когда приходит муж в магазин то, что он обнаруживает? Указанные в списке товары оказываются в разных частях магазина. Обычно список длинный, поэтому запомнить что-либо, что было уже куплено достаточно трудно. На это накладывается, что какие-то отделы временно закрыты — идет выгрузка товаров, какого-то товара нет в продаже, плюс толчея, зимняя одежда. Более опытные товарищи ходят с карандашом или ручкой с очень озабоченным видом и постоянно смотрят в свой список. Но, в итоге, все равно, что-нибудь да забудешь купить. По своему опыту могу сказать, что это «что-нибудь» окажется самым важным, из-за чего вообще и стоило ехать в магазин.

Какой список был бы удобен мужу? Тот, в котором все товары сгруппированы по отделам, отдельные группы идут в очередности, соответствующей порядку обхода магазина. Например, для магазина, в который хожу я было бы удобно сгруппировать товары следующим образом:

  • Батарейки
  • Детские тетради
  • Ручка
  • Вода
  • Сок
  • Сахар
  • Морковь
  • Апельсины
  • Яблоки
  • Виноград
  • Картофель
  • Масло
  • Хлеб
  • Молоко
  • Сметана
  • Мука
  • Детская игрушка

Еще одно важное наблюдение — невозможно по самим абстракциям определить насколько удачными они получились. Это можно сделать, только если мы попытаемся их использовать на практике. И тут уж выясняется, что одни абстракции лучше подходят для задачи, а другие — хуже. А если еще немного изменить исходные условия, то и прежний «хороший» набор абстракций уже может не работать. Например, второй список покупок из примера перестанет работать, если прийти с ним в другой магазин с иным порядком выкладки товаров. Он станет ничем не лучше, чем первый.
Отсюда вывод — невозможно придумать набор классов, который подойдет на все случаи жизни. В статье The Open-Closed Principle это называется стратегическая замкнутость.

Естественный вопрос, а как сразу создавать хорошие абстракции. Увы, но на этот счет нет точного ответа. Зато со временем выработался набор практик, который говорит, как надо поступать, и обещает, что в этом случае будет хороший результат. К таким практикам относится рефакторинг, стандарты кодирования, code review, объектная гимнастика и т.д. Цель данных практик — направить ход мыслей группы разработчиков в одном направлении, тогда шансов, что чужой код будет понятнее, станет больше. Отношение к каждой из практик у отдельно взятого человека зависит лишь от приобретенного им опыта использования практики. Часто слова «Это не работает» надо интерпретировать как «Я пробовал — у меня не получилось». Нет никаких объективных аргументов «ЗА», равно как и «ПРОТИВ».

Так зачем нужно тогда ООП?

Проведем параллели между естественным языком и ООП

естественный язык ООП
Слово класс
Правила Синтаксис
Жанр Архитектура
литературные приемы паттерны

Любые свои мысли человек выражает словами естественного языка. Есть два типа задач:

  1. Для решения надо хорошо знать сам язык. Например, чтобы написать Войну и Мир.
  2. Сложность не зависит от языка. Неважно сколько и какие языки Вы знаете. Это никак не помогает при решении. Например, теорема Ферма.

ООП — это инструмент, который создавался с прицелом на большие по размеру программы. Но, это всего лишь один из инструментов, который потребуется, чтобы написать крупный проект.

Меня всегда удивляют, статьи в стиле Почему я люблю X или Почему я не люблю X. Все прекрасно понимают, что X — инструмент. Ведь нет же таких статей про лопату. Хотя, кто знает, ведь ООП существует несколько десятилетий, а лопата несколько тысяч, и быть может где-нибудь в в каменном веке шли жестокие холивары на тему, что лучше лопатка мамонта или мотыга из камня?

Литература по теме

1. Гради Буч Объектно-ориентированный анализ и проектирование с примерами приложений на С++
Данная книга в представлении не нуждается. Одна из наиболее цитируемых книг по программированию.
2. Барбара Минто Принципы Пирамиды Минто.
Работая консультантом McKinsey Барбара Минто создала свой собственный метод написания аналитических документов, основанный.на том, как человек воспринимает информацию. В книге достаточно много места уделено принципам группировки и обобщения.
3. Роберт Мартин (Uncle Bob)
Роберт Мартин написал серию статей и книг про принципы ООП. Наиболее известные из них S.O.L.I..D. На русском языке вышла книжка Роберт Мартин Быстрая разработка программ. Принципы, примеры, практика, в которой описаны эти принципы. Но на мой взгляд про них лучше прочитать в статьях The Single Responsibility Principle, The Open-Closed Principle, The Liskov Substitution Principle, The Interface Segregation Principle, The Dependency Inversion Principle.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Отвечал он неохотно скиснувшим голосом исправьте ошибки
  • Ответы на тесты нмо профилактика ошибок идентификации пациента
  • Ответы на тесты нмо ошибки при проведении экг
  • Ответы на тест сестринские ошибки лекарственной помощи итоговое тестирование
  • Ответы на вопросы нмо сестринские ошибки лекарственной помощи

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии