Из Википедии, бесплатной энциклопедии
Перейти к навигации Перейти к поиску

Объектно- ориентированное программирование(ООП) - этопарадигма программирования,основанная на концепции «объектов», которые могут содержатьданныеи код: данные в формеполей(часто называемыеатрибутамиилисвойствами) и код в форме процедур. (часто называемые методами ).

Особенностью объектов является то, что собственные процедуры объекта могут обращаться к полям данных самого себя и часто изменять их (объекты имеют понятие thisили self). В ООП компьютерные программы создаются путем создания их из взаимодействующих друг с другом объектов. [1] [2] ООП-языки разнообразны, но самые популярные из них основаны на классах , что означает, что объекты являются экземплярами классов , которые также определяют их типы .

Многие из наиболее широко используемых языков программирования (например, C ++, Java, Python и т.д.), мульти-парадигмы , и они поддерживают объектно-ориентированное программирование в большей или меньшей степени, как правило , в сочетании с императива , процедурного программирования . Важные объектно-ориентированные языки включают: (порядок списков на основе индекса TIOBE ) Java , C ++ , C # , Python , R , PHP , Visual Basic.NET , JavaScript , Ruby , Perl , Object Pascal , Objective-C , Dart , Swift , Scala , Kotlin , Common Lisp , MATLAB и Smalltalk .

Особенности [ править ]

В объектно-ориентированном программировании используются объекты, но не все связанные методы и структуры поддерживаются непосредственно на языках, которые утверждают, что поддерживают ООП. Перечисленные ниже функции являются общими для языков, которые считаются строго классовыми и объектно-ориентированными (или мультипарадигмальными с поддержкой ООП), с упомянутыми заметными исключениями. [3] [4] [5] [6]

Совместно с языками, отличными от ООП [ править ]

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

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

Объекты и классы [ править ]

Языки, поддерживающие объектно-ориентированное программирование (ООП), обычно используют наследование для повторного использования кода и расширяемости в форме классов или прототипов . Те, кто использует классы, поддерживают две основные концепции:

  • Классы - определения формата данных и доступных процедур для данного типа или класса объекта; могут также содержать сами данные и процедуры (известные как методы класса), т. е. классы содержат элементы данных и функции-члены
  • Объекты - экземпляры классов

Иногда предметы соответствуют вещам, которые можно найти в реальном мире. Например, графическая программа может иметь такие объекты, как «круг», «квадрат», «меню». В системе покупок в Интернете могут быть такие объекты, как «корзина», «покупатель» и «продукт». [7] Иногда объекты представляют собой более абстрактные сущности, такие как объект, представляющий открытый файл, или объект, который предоставляет услугу перевода измерений из обычных в США в метрические.

Объектно-ориентированное программирование - это больше, чем просто классы и объекты; это целая парадигма программирования, основанная на [ sic ] объектах (структурах данных), которые содержат поля данных и методы. Это необходимо понимать; использование классов для организации множества не связанных между собой методов не является объектной ориентацией.

Джунад Али, Освоение шаблонов проектирования PHP [8]

Говорят, что каждый объект является экземпляром определенного класса (например, объект с полем его имени, установленным на «Мэри», может быть экземпляром класса Employee). Процедуры в объектно-ориентированном программировании известны как методы ; переменные также известны как поля , члены, атрибуты или свойства. Это приводит к следующим условиям:

  • Переменные класса - относятся к классу в целом ; есть только одна копия каждого
  • Переменные или атрибуты экземпляра - данные, принадлежащие отдельным объектам ; у каждого объекта есть своя копия каждого
  • Переменные-члены - относятся как к переменным класса, так и к переменным экземпляра, которые определены конкретным классом.
  • Методы класса - принадлежат к классу в целом и имеют доступ только к переменным класса и входным данным из вызова процедуры.
  • Методы экземпляра - принадлежат к отдельным объектам и имеют доступ к переменным экземпляра для конкретного объекта, для которого они вызываются, входных данных и переменных класса.

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

Объектно-ориентированное программирование, использующее классы, иногда называют программированием на основе классов , в то время как программирование на основе прототипов обычно не использует классы. В результате для определения понятий объекта и экземпляра используется существенно отличающаяся, но аналогичная терминология .

В некоторых языках классы и объекты могут быть составлены с использованием других концепций, таких как трейты и миксины .

На основе классов и на основе прототипов [ править ]

В языках, основанных на классах, классы определяются заранее, и объекты создаются на основе классов. Если два объекта - яблоко и апельсин - созданы из класса Fruit , они по своей сути являются фруктами, и вы гарантированно сможете обращаться с ними таким же образом; например , программист может рассчитывать на существовании тех же атрибуты , такие как цвет или sugar_content или is_ripe .

В языках, основанных на прототипах, объекты являются первичными сущностями. Никаких классов даже не существует. Прототип объекта является еще одним объектом , к которому прикреплен объект. У каждого объекта есть одна ссылка на прототип (и только одна). Новые объекты могут быть созданы на основе уже существующих объектов, выбранных в качестве их прототипа. Вы можете назвать два разных объекта яблоком и апельсином фруктом, если объект фрукт существует, а яблоко и апельсин имеют фрукт в качестве своего прототипа. Идея фруктового класса существует не в явном виде, а каккласс эквивалентности объектов, имеющих один и тот же прототип. Атрибуты и методы прототипа будут делегированы всем объектам класса эквивалентности , определяемых этим прототипом. Атрибуты и методы, которыми индивидуально владеет объект, не могут совместно использоваться другими объектами того же класса эквивалентности; например , атрибут sugar_content может быть неожиданно нет в яблоке . Через прототип можно реализовать только однократное наследование .

Динамическая отправка / передача сообщений [ править ]

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

Вызов метода также известен как передача сообщений . Он концептуализирован как сообщение (имя метода и его входные параметры), передаваемое объекту для отправки.

Инкапсуляция [ править ]

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

Если класс не позволяет вызывающему коду получать доступ к внутренним данным объекта и разрешает доступ только через методы, это сильная форма абстракции или сокрытия информации, известная как инкапсуляция . Некоторые языки (например, Java) позволяют классам явно применять ограничения доступа, например, обозначая внутренние данные с помощью privateключевого слова, а методы, предназначенные для использования кодом вне класса, с помощью этого publicключевого слова. Методы также могут быть спроектированы общедоступными, частными или промежуточными уровнями, такими как protected(который разрешает доступ из того же класса и его подклассов, но не объектов другого класса). В других языках (например, Python) это применяется только по соглашению (например, privateметоды могут иметь имена, начинающиеся с подчеркивания.). Инкапсуляция предотвращает взаимодействие внешнего кода с внутренней работой объекта. Это облегчает рефакторинг кода , например, позволяя автору класса изменять способ представления данных объектами этого класса внутри без изменения внешнего кода (при условии, что вызовы «общедоступных» методов работают одинаково). Это также побуждает программистов помещать весь код, связанный с определенным набором данных, в один и тот же класс, который упорядочивает его для облегчения понимания другими программистами. Инкапсуляция - это метод, который способствует разделению .

Состав, наследование и делегирование [ править ]

Объекты могут содержать другие объекты в своих переменных экземпляра; это известно как композиция объекта . Например, объект в классе Employee может содержать (напрямую или через указатель) объект в классе Address в дополнение к своим собственным переменным экземпляра, таким как «first_name» и «position». Композиция объекта используется для представления отношений типа «есть-а»: у каждого сотрудника есть адрес, поэтому каждый объект Employee имеет доступ к месту для хранения объекта Address (либо непосредственно встроенного в себя, либо в отдельном месте, адресуемом через указатель) .

Языки, поддерживающие классы, почти всегда поддерживают наследование. Это позволяет классам быть организованными в иерархию, которая представляет отношения типа «есть тип». Например, класс Employee может быть унаследован от класса Person. Все данные и методы, доступные для родительского класса, также появляются в дочернем классе с такими же именами. Например, класс Person может определять переменные first_name и last_name с помощью метода make_full_name (). Они также будут доступны в классе Employee, который может добавлять переменные «должность» и «зарплата». Этот метод позволяет легко повторно использовать одни и те же процедуры и определения данных в дополнение к потенциально интуитивному отображению реальных отношений. Вместо того, чтобы использовать таблицы базы данных и подпрограммы программирования, разработчик использует объекты, с которыми пользователь может быть более знаком:объекты из своего домена приложения. [9]

Подклассы могут переопределять методы, определенные суперклассами. На некоторых языках разрешено множественное наследование , хотя это может усложнить разрешение переопределений. Некоторые языки имеют специальную поддержку миксинов , хотя на любом языке с множественным наследованием миксин - это просто класс, который не представляет отношения типа «есть тип». Примеси обычно используются для добавления одних и тех же методов к нескольким классам. Например, класс UnicodeConversionMixin может предоставлять метод unicode_to_ascii () при включении в класс FileReader и класс WebPageScraper, которые не имеют общего родителя.

Абстрактные классы не могут быть преобразованы в объекты; они существуют только с целью наследования другим «конкретным» классам, которые могут быть созданы. В Java это finalключевое слово может использоваться для предотвращения создания подкласса.

Доктрина композиции над наследованием выступает за реализацию отношений типа «есть-а» с использованием композиции вместо наследования. Например, вместо наследования от класса Person, класс Employee может предоставить каждому объекту Employee внутренний объект Person, который затем имеет возможность скрыть от внешнего кода, даже если класс Person имеет много общедоступных атрибутов или методов. Некоторые языки, например Go, вообще не поддерживают наследование.

Принцип « открытость / закрытость » утверждает, что классы и функции «должны быть открыты для расширения, но закрыты для модификации».

Делегирование - это еще одна языковая функция, которую можно использовать как альтернативу наследованию.

Полиморфизм [ править ]

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

Например, объекты типа Circle и Square являются производными от общего класса Shape. Функция Draw для каждого типа Shape реализует то, что необходимо для рисования самого себя, в то время как вызывающий код может оставаться безразличным к конкретному типу рисуемого Shape.

Это еще один тип абстракции, который упрощает код, внешний по отношению к иерархии классов, и обеспечивает четкое разделение задач .

Открытая рекурсия [ править ]

В языках, поддерживающих открытую рекурсию , методы объекта могут вызывать другие методы для того же объекта (включая самих себя), обычно с использованием специальной переменной или ключевого слова, называемого thisили self. Эта переменная имеет позднюю привязку ; он позволяет методу, определенному в одном классе, вызывать другой метод, который определен позже в каком-либо его подклассе.

История [ править ]

Нотация UML для класса. Этот класс Button имеет переменные для данных и функций . Посредством наследования подкласс может быть создан как подмножество класса Button. Объекты - это экземпляры класса.

Терминология «объекты» и «ориентированный» в современном смысле объектно-ориентированного программирования впервые появилась в Массачусетском технологическом институте в конце 1950-х - начале 1960-х годов. В среде группы искусственного интеллекта еще в 1960 году «объект» мог относиться к идентифицированным элементам ( атомам LISP ) со свойствами (атрибутами); [10] [11] Алан Кей позже процитировал подробное понимание внутреннего устройства LISP как сильное влияние на его мышление в 1966 году. [12]

Я думал об объектах, которые похожи на биологические клетки и / или отдельные компьютеры в сети, которые могут общаться только с помощью сообщений (так что обмен сообщениями появился в самом начале - потребовалось время, чтобы увидеть, как отправлять сообщения на языке программирования, достаточно эффективно полезный).

Алан Кей, [12]

Другим ранним примером MIT был Sketchpad, созданный Иваном Сазерлендом в 1960–61; в глоссарии технического отчета 1963 года, основанного на его диссертации о Sketchpad, Сазерленд определил понятия «объект» и «экземпляр» (с концепцией класса, охватываемой «хозяином» или «определением»), хотя и специализированными на графическом взаимодействии. [13] Кроме того, версия MIT ALGOL , AED-0, установила прямую связь между структурами данных («сплетения» на этом диалекте) и процедурами, предварительно сконфигурировав то, что позже было названо «сообщениями», «методами» и «функциями-членами». ". [14] [15]

В 1962 году Кристен Найгаард инициировала проект языка моделирования в Норвежском вычислительном центре , основанный на его предыдущем использовании моделирования Монте-Карло и его работе по концептуализации реальных систем. Оле-Йохан Даль официально присоединился к проекту, и язык программирования Simula был разработан для работы на универсальном автоматическом компьютере (UNIVAC) 1107. Simula представила важные концепции, которые сегодня являются неотъемлемой частью объектно-ориентированного программирования, такие как класс и объект , наследование. и динамическое связывание . [16]Simula также была разработана с учетом программирования и безопасности данных . В целях безопасности программирования был реализован процесс обнаружения, так что с помощью подсчета ссылок сборщик мусора в крайнем случае удалял неиспользуемые объекты в оперативной памяти (RAM). Но хотя идея объектов данных уже была создана к 1965 году, инкапсуляция данных через уровни области видимости для переменных , таких как частные (-) и общедоступные (+), не была реализована в Simula, поскольку для этого потребовалось бы, чтобы процедуры доступа были также скрыт. [17]

In the early stages, Simula was supposed to be a procedure package for the programming language ALGOL 60. Dissatisfied with the restrictions imposed by ALGOL the researchers decided to develop Simula into a fully-fledged programming language, which used the UNIVAC ALGOL 60 compiler. Simula was promoted by Dahl and Nygaard throughout 1965 and 1966, leading to increasing use of the programming language in Sweden, Germany and the Soviet Union. In 1968, the language became widely available through the Burroughs B5500 computers, and was later also implemented on the URAL-16 computer. In 1966, Dahl and Nygaard wrote a Simula compiler. They became preoccupied with putting into practice Tony Hoare's record class concept, which had been implemented in the free-form, English-like general-purpose simulation language SIMSCRIPT. They settled for a generalised process concept with record class properties, and a second layer of prefixes. Through prefixing a process could reference its predecessor and have additional properties. Simula thus introduced the class and subclass hierarchy, and the possibility of generating objects from these classes.

A Simula 67 compiler was launched for the System/360 and System/370 IBM mainframe computers in 1972.[16] In the same year a Simula 67 compiler was launched free of charge for the French CII 10070 and CII Iris 80 mainframe computers. By 1974, the Association of Simula Users had members in 23 different countries. Early 1975 a Simula 67 compiler was released free of charge for the DECsystem-10 mainframe family. By August the same year the DECsystem-10 Simula 67 compiler had been installed at 28 sites, 22 of them in North America. The object-oriented Simula programming language was used mainly by researchers involved with physical modelling, such as models to study and improve the movement of ships and their content through cargo ports.[16]

In the 1970s, the first version of the Smalltalk programming language was developed at Xerox PARC by Alan Kay, Dan Ingalls and Adele Goldberg. Smaltalk-72 included a programming environment and was dynamically typed, and at first was interpreted, not compiled. Smalltalk became noted for its application of object orientation at the language-level and its graphical development environment. Smalltalk went through various versions and interest in the language grew.[18] While Smalltalk was influenced by the ideas introduced in Simula 67 it was designed to be a fully dynamic system in which classes could be created and modified dynamically.[19]

In the 1970s, Smalltalk influenced the Lisp community to incorporate object-based techniques that were introduced to developers via the Lisp machine. Experimentation with various extensions to Lisp (such as LOOPS and Flavors introducing multiple inheritance and mixins) eventually led to the Common Lisp Object System, which integrates functional programming and object-oriented programming and allows extension via a Meta-object protocol. In the 1980s, there were a few attempts to design processor architectures that included hardware support for objects in memory but these were not successful. Examples include the Intel iAPX 432 and the Linn Smart Rekursiv.

In 1981, Goldberg edited the August issue of Byte Magazine, introducing Smalltalk and object-oriented programming to a wider audience. In 1986, the Association for Computing Machinery organised the first Conference on Object-Oriented Programming, Systems, Languages, and Applications (OOPSLA), which was unexpectedly attended by 1,000 people. In the mid-1980s Objective-C was developed by Brad Cox, who had used Smalltalk at ITT Inc., and Bjarne Stroustrup, who had used Simula for his PhD thesis, eventually went to create the object-oriented C++.[18] In 1985, Bertrand Meyer also produced the first design of the Eiffel language. Focused on software quality, Eiffel is a purely object-oriented programming language and a notation supporting the entire software lifecycle. Meyer described the Eiffel software development method, based on a small number of key ideas from software engineering and computer science, in Object-Oriented Software Construction. Essential to the quality focus of Eiffel is Meyer's reliability mechanism, Design by Contract, which is an integral part of both the method and language.

The TIOBE programming language popularity index graph from 2002 to 2018. In the 2000s the object-oriented Java (blue) and the procedural C (black) competed for the top position.

In the early and mid-1990s object-oriented programming developed as the dominant programming paradigm when programming languages supporting the techniques became widely available. These included Visual FoxPro 3.0,[20][21][22] C++,[23] and Delphi[citation needed]. Its dominance was further enhanced by the rising popularity of graphical user interfaces, which rely heavily upon object-oriented programming techniques. An example of a closely related dynamic GUI library and OOP language can be found in the Cocoa frameworks on Mac OS X, written in Objective-C, an object-oriented, dynamic messaging extension to C based on Smalltalk. OOP toolkits also enhanced the popularity of event-driven programming (although this concept is not limited to OOP).

At ETH Zürich, Niklaus Wirth and his colleagues had also been investigating such topics as data abstraction and modular programming (although this had been in common use in the 1960s or earlier). Modula-2 (1978) included both, and their succeeding design, Oberon, included a distinctive approach to object orientation, classes, and such.

Object-oriented features have been added to many previously existing languages, including Ada, BASIC, Fortran, Pascal, and COBOL. Adding these features to languages that were not initially designed for them often led to problems with compatibility and maintainability of code.

More recently, a number of languages have emerged that are primarily object-oriented, but that are also compatible with procedural methodology. Two such languages are Python and Ruby. Probably the most commercially important recent object-oriented languages are Java, developed by Sun Microsystems, as well as C# and Visual Basic.NET (VB.NET), both designed for Microsoft's .NET platform. Each of these two frameworks shows, in its own way, the benefit of using OOP by creating an abstraction from implementation. VB.NET and C# support cross-language inheritance, allowing classes defined in one language to subclass classes defined in the other language.

OOP languages[edit]

Simula (1967) is generally accepted as being the first language with the primary features of an object-oriented language. It was created for making simulation programs, in which what came to be called objects were the most important information representation. Smalltalk (1972 to 1980) is another early example, and the one with which much of the theory of OOP was developed. Concerning the degree of object orientation, the following distinctions can be made:

  • Languages called "pure" OO languages, because everything in them is treated consistently as an object, from primitives such as characters and punctuation, all the way up to whole classes, prototypes, blocks, modules, etc. They were designed specifically to facilitate, even enforce, OO methods. Examples: Ruby, Scala, Smalltalk, Eiffel, Emerald,[24] JADE, Self, Raku.
  • Languages designed mainly for OO programming, but with some procedural elements. Examples: Java, Python, C++, C#, Delphi/Object Pascal, VB.NET.
  • Languages that are historically procedural languages, but have been extended with some OO features. Examples: PHP, Perl, Visual Basic (derived from BASIC), MATLAB, COBOL 2002, Fortran 2003, ABAP, Ada 95, Pascal.
  • Languages with most of the features of objects (classes, methods, inheritance), but in a distinctly original form. Examples: Oberon (Oberon-1 or Oberon-2).
  • Languages with abstract data type support which may be used to resemble OO programming, but without all features of object-orientation. This includes object-based and prototype-based languages. Examples: JavaScript, Lua, Modula-2, CLU.
  • Chameleon languages that support multiple paradigms, including OO. Tcl stands out among these for TclOO, a hybrid object system that supports both prototype-based programming and class-based OO.

OOP in dynamic languages[edit]

In recent years, object-oriented programming has become especially popular in dynamic programming languages. Python, PowerShell, Ruby and Groovy are dynamic languages built on OOP principles, while Perl and PHP have been adding object-oriented features since Perl 5 and PHP 4, and ColdFusion since version 6.

The Document Object Model of HTML, XHTML, and XML documents on the Internet has bindings to the popular JavaScript/ECMAScript language. JavaScript is perhaps the best known prototype-based programming language, which employs cloning from prototypes rather than inheriting from a class (contrast to class-based programming). Another scripting language that takes this approach is Lua.

OOP in a network protocol[edit]

The messages that flow between computers to request services in a client-server environment can be designed as the linearizations of objects defined by class objects known to both the client and the server. For example, a simple linearized object would consist of a length field, a code point identifying the class, and a data value. A more complex example would be a command consisting of the length and code point of the command and values consisting of linearized objects representing the command's parameters. Each such command must be directed by the server to an object whose class (or superclass) recognizes the command and is able to provide the requested service. Clients and servers are best modeled as complex object-oriented structures. Distributed Data Management Architecture (DDM) took this approach and used class objects to define objects at four levels of a formal hierarchy:

  • Fields defining the data values that form messages, such as their length, code point and data values.
  • Objects and collections of objects similar to what would be found in a Smalltalk program for messages and parameters.
  • Managers similar to IBM i Objects, such as a directory to files and files consisting of metadata and records. Managers conceptually provide memory and processing resources for their contained objects.
  • A client or server consisting of all the managers necessary to implement a full processing environment, supporting such aspects as directory services, security and concurrency control.

The initial version of DDM defined distributed file services. It was later extended to be the foundation of Distributed Relational Database Architecture (DRDA).

Design patterns[edit]

Challenges of object-oriented design are addressed by several approaches. Most common is known as the design patterns codified by Gamma et al.. More broadly, the term "design patterns" can be used to refer to any general, repeatable, solution pattern to a commonly occurring problem in software design. Some of these commonly occurring problems have implications and solutions particular to object-oriented development.

Inheritance and behavioral subtyping[edit]

It is intuitive to assume that inheritance creates a semantic "is a" relationship, and thus to infer that objects instantiated from subclasses can always be safely used instead of those instantiated from the superclass. This intuition is unfortunately false in most OOP languages, in particular in all those that allow mutable objects. Subtype polymorphism as enforced by the type checker in OOP languages (with mutable objects) cannot guarantee behavioral subtyping in any context. Behavioral subtyping is undecidable in general, so it cannot be implemented by a program (compiler). Class or object hierarchies must be carefully designed, considering possible incorrect uses that cannot be detected syntactically. This issue is known as the Liskov substitution principle.

Gang of Four design patterns[edit]

Design Patterns: Elements of Reusable Object-Oriented Software is an influential book published in 1994 by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, often referred to humorously as the "Gang of Four". Along with exploring the capabilities and pitfalls of object-oriented programming, it describes 23 common programming problems and patterns for solving them. As of April 2007, the book was in its 36th printing.

The book describes the following patterns:

  • Creational patterns (5): Factory method pattern, Abstract factory pattern, Singleton pattern, Builder pattern, Prototype pattern
  • Structural patterns (7): Adapter pattern, Bridge pattern, Composite pattern, Decorator pattern, Facade pattern, Flyweight pattern, Proxy pattern
  • Behavioral patterns (11): Chain-of-responsibility pattern, Command pattern, Interpreter pattern, Iterator pattern, Mediator pattern, Memento pattern, Observer pattern, State pattern, Strategy pattern, Template method pattern, Visitor pattern

Object-orientation and databases[edit]

Both object-oriented programming and relational database management systems (RDBMSs) are extremely common in software today. Since relational databases don't store objects directly (though some RDBMSs have object-oriented features to approximate this), there is a general need to bridge the two worlds. The problem of bridging object-oriented programming accesses and data patterns with relational databases is known as object-relational impedance mismatch. There are a number of approaches to cope with this problem, but no general solution without downsides.[25] One of the most common approaches is object-relational mapping, as found in IDE languages such as Visual FoxPro and libraries such as Java Data Objects and Ruby on Rails' ActiveRecord.

There are also object databases that can be used to replace RDBMSs, but these have not been as technically and commercially successful as RDBMSs.

Real-world modeling and relationships[edit]

OOP can be used to associate real-world objects and processes with digital counterparts. However, not everyone agrees that OOP facilitates direct real-world mapping (see Criticism section) or that real-world mapping is even a worthy goal; Bertrand Meyer argues in Object-Oriented Software Construction[26] that a program is not a model of the world but a model of some part of the world; "Reality is a cousin twice removed". At the same time, some principal limitations of OOP have been noted.[27]For example, the circle-ellipse problem is difficult to handle using OOP's concept of inheritance.

However, Niklaus Wirth (who popularized the adage now known as Wirth's law: "Software is getting slower more rapidly than hardware becomes faster") said of OOP in his paper, "Good Ideas through the Looking Glass", "This paradigm closely reflects the structure of systems 'in the real world', and it is therefore well suited to model complex systems with complex behaviours"[28] (contrast KISS principle).

Steve Yegge and others noted that natural languages lack the OOP approach of strictly prioritizing things (objects/nouns) before actions (methods/verbs).[29] This problem may cause OOP to suffer more convoluted solutions than procedural programming.[30]

OOP and control flow[edit]

OOP was developed to increase the reusability and maintainability of source code.[31] Transparent representation of the control flow had no priority and was meant to be handled by a compiler. With the increasing relevance of parallel hardware and multithreaded coding, developing transparent control flow becomes more important, something hard to achieve with OOP.[32][33][34][35]

Responsibility- vs. data-driven design[edit]

Responsibility-driven design defines classes in terms of a contract, that is, a class should be defined around a responsibility and the information that it shares. This is contrasted by Wirfs-Brock and Wilkerson with data-driven design, where classes are defined around the data-structures that must be held. The authors hold that responsibility-driven design is preferable.

SOLID and GRASP guidelines[edit]

SOLID is a mnemonic invented by Michael Feathers that stands for and advocates five programming practices:

  • Single responsibility principle
  • Open/closed principle
  • Liskov substitution principle
  • Interface segregation principle
  • Dependency inversion principle

GRASP (General Responsibility Assignment Software Patterns) is another set of guidelines advocated by Craig Larman.

Criticism[edit]

The OOP paradigm has been criticised for a number of reasons, including not meeting its stated goals of reusability and modularity,[36][37] and for overemphasizing one aspect of software design and modeling (data/objects) at the expense of other important aspects (computation/algorithms).[38][39]

Luca Cardelli has claimed that OOP code is "intrinsically less efficient" than procedural code, that OOP can take longer to compile, and that OOP languages have "extremely poor modularity properties with respect to class extension and modification", and tend to be extremely complex.[36] The latter point is reiterated by Joe Armstrong, the principal inventor of Erlang, who is quoted as saying:[37]

The problem with object-oriented languages is they've got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.

A study by Potok et al. has shown no significant difference in productivity between OOP and procedural approaches.[40]

Christopher J. Date stated that critical comparison of OOP to other technologies, relational in particular, is difficult because of lack of an agreed-upon and rigorous definition of OOP;[41] however, Date and Darwen have proposed a theoretical foundation on OOP that uses OOP as a kind of customizable type system to support RDBMS.[42]

In an article Lawrence Krubner claimed that compared to other languages (LISP dialects, functional languages, etc.) OOP languages have no unique strengths, and inflict a heavy burden of unneeded complexity.[43]

Alexander Stepanov compares object orientation unfavourably to generic programming:[38]

I find OOP technically unsound. It attempts to decompose the world in terms of interfaces that vary on a single type. To deal with the real problems you need multisorted algebras — families of interfaces that span multiple types. I find OOP philosophically unsound. It claims that everything is an object. Even if it is true it is not very interesting — saying that everything is an object is saying nothing at all.

Paul Graham has suggested that OOP's popularity within large companies is due to "large (and frequently changing) groups of mediocre programmers". According to Graham, the discipline imposed by OOP prevents any one programmer from "doing too much damage".[44]

Leo Brodie has suggested a connection between the standalone nature of objects and a tendency to duplicate code[45] in violation of the don't repeat yourself principle[46] of software development.

Steve Yegge noted that, as opposed to functional programming:[47]

Object Oriented Programming puts the Nouns first and foremost. Why would you go to such lengths to put one part of speech on a pedestal? Why should one kind of concept take precedence over another? It's not as if OOP has suddenly made verbs less important in the way we actually think. It's a strangely skewed perspective.

Rich Hickey, creator of Clojure, described object systems as overly simplistic models of the real world. He emphasized the inability of OOP to model time properly, which is getting increasingly problematic as software systems become more concurrent.[39]

Eric S. Raymond, a Unix programmer and open-source software advocate, has been critical of claims that present object-oriented programming as the "One True Solution", and has written that object-oriented programming languages tend to encourage thickly layered programs that destroy transparency.[48] Raymond compares this unfavourably to the approach taken with Unix and the C programming language.[48]

Rob Pike, a programmer involved in the creation of UTF-8 and Go, has called object-oriented programming "the Roman numerals of computing"[49] and has said that OOP languages frequently shift the focus from data structures and algorithms to types.[50] Furthermore, he cites an instance of a Java professor whose "idiomatic" solution to a problem was to create six new classes, rather than to simply use a lookup table.[51]

Formal semantics[edit]

Objects are the run-time entities in an object-oriented system. They may represent a person, a place, a bank account, a table of data, or any item that the program has to handle.

There have been several attempts at formalizing the concepts used in object-oriented programming. The following concepts and constructs have been used as interpretations of OOP concepts:

  • co algebraic data types[52]
  • abstract data types (which have existential types) allow the definition of modules but these do not support dynamic dispatch
  • recursive types
  • encapsulated state
  • inheritance
  • records are basis for understanding objects if function literals can be stored in fields (like in functional-programming languages), but the actual calculi need be considerably more complex to incorporate essential features of OOP. Several extensions of System F<: that deal with mutable objects have been studied;[53] these allow both subtype polymorphism and parametric polymorphism (generics)

Attempts to find a consensus definition or theory behind objects have not proven very successful (however, see Abadi & Cardelli, A Theory of Objects[53] for formal definitions of many OOP concepts and constructs), and often diverge widely. For example, some definitions focus on mental activities, and some on program structuring. One of the simpler definitions is that OOP is the act of using "map" data structures or arrays that can contain functions and pointers to other maps, all with some syntactic and scoping sugar on top. Inheritance can be performed by cloning the maps (sometimes called "prototyping").

See also[edit]

  • Comparison of programming languages (object-oriented programming)
  • Comparison of programming paradigms
  • Component-based software engineering
  • Design by contract
  • Object association
  • Object database
  • Object modeling language
  • Object-oriented analysis and design
  • Object-relational impedance mismatch (and The Third Manifesto)
  • Object-relational mapping

Systems[edit]

  • CADES
  • Common Object Request Broker Architecture (CORBA)
  • Distributed Component Object Model
  • Distributed Data Management Architecture
  • Jeroo

Modeling languages[edit]

  • IDEF4
  • Interface description language
  • Lepus3
  • UML

References[edit]

  1. ^ Kindler, E.; Krivy, I. (2011). "Object-Oriented Simulation of systems with sophisticated control". International Journal of General Systems: 313–343. Cite journal requires |journal= (help)
  2. ^ Lewis, John; Loftus, William (2008). Java Software Solutions Foundations of Programming Design 6th ed. Pearson Education Inc. ISBN 978-0-321-53205-3., section 1.6 "Object-Oriented Programming"
  3. ^ Deborah J. Armstrong. The Quarks of Object-Oriented Development. A survey of nearly 40 years of computing literature which identified a number of fundamental concepts found in the large majority of definitions of OOP, in descending order of popularity: Inheritance, Object, Class, Encapsulation, Method, Message Passing, Polymorphism, and Abstraction.
  4. ^ John C. Mitchell, Concepts in programming languages, Cambridge University Press, 2003, ISBN 0-521-78098-5, p.278. Lists: Dynamic dispatch, abstraction, subtype polymorphism, and inheritance.
  5. ^ Michael Lee Scott, Programming language pragmatics, Edition 2, Morgan Kaufmann, 2006, ISBN 0-12-633951-1, p. 470. Lists encapsulation, inheritance, and dynamic dispatch.
  6. ^ Pierce, Benjamin (2002). Types and Programming Languages. MIT Press. ISBN 978-0-262-16209-8., section 18.1 "What is Object-Oriented Programming?" Lists: Dynamic dispatch, encapsulation or multi-methods (multiple dispatch), subtype polymorphism, inheritance or delegation, open recursion ("this"/"self")
  7. ^ Booch, Grady (1986). Software Engineering with Ada. Addison Wesley. p. 220. ISBN 978-0-8053-0608-8. Perhaps the greatest strength of an object-oriented approach to development is that it offers a mechanism that captures a model of the real world.
  8. ^ Ali, Junade (28 September 2016). Mastering PHP Design Patterns | PACKT Books (1 ed.). Birmingham, England, UK: Packt Publishing Limited. p. 11. ISBN 978-1-78588-713-0. Retrieved 11 December 2017.
  9. ^ Jacobsen, Ivar; Magnus Christerson; Patrik Jonsson; Gunnar Overgaard (1992). Object Oriented Software Engineering. Addison-Wesley ACM Press. pp. 43–69. ISBN 978-0-201-54435-0.
  10. ^ McCarthy, J.; Brayton, R.; Edwards, D.; Fox, P.; Hodes, L.; Luckham, D.; Maling, K.; Park, D.; Russell, S. (March 1960). "LISP I Programmers Manual" (PDF). Boston, Massachusetts: Artificial Intelligence Group, M.I.T. Computation Center and Research Laboratory: 88f. Archived from the original (PDF) on 17 July 2010. In the local M.I.T. patois, association lists [of atomic symbols] are also referred to as "property lists", and atomic symbols are sometimes called "objects". Cite journal requires |journal= (help)
  11. ^ McCarthy, John; Abrahams, Paul W.; Edwards, Daniel J.; Hart, swapnil d.; Levin, Michael I. (1962). LISP 1.5 Programmer's Manual. MIT Press. p. 105. ISBN 978-0-262-13011-0. Object — a synonym for atomic symbol
  12. ^ a b "Dr. Alan Kay on the Meaning of "Object-Oriented Programming"". 2003. Retrieved 11 February 2010.
  13. ^ Sutherland, I. E. (30 January 1963). "Sketchpad: A Man-Machine Graphical Communication System". Technical Report No. 296, Lincoln Laboratory, Massachusetts Institute of Technology via Defense Technical Information Center (stinet.dtic.mil). Retrieved 17 July 2019.
  14. ^ The Development of the Simula Languages, Kristen Nygaard, Ole-Johan Dahl, p.254 Uni-kl.ac.at
  15. ^ Ross, Doug. "The first software engineering language". LCS/AI Lab Timeline. MIT Computer Science and Artificial Intelligence Laboratory. Retrieved 13 May 2010.
  16. ^ a b c Holmevik, Jan Rune (1994). "Compiling Simula: A historical study of technological genesis" (PDF). IEEE Annals of the History of Computing. 16 (4): 25–37. doi:10.1109/85.329756. Archived from the original (PDF) on 30 August 2017. Retrieved 3 March 2018.
  17. ^ Dahl, Ole Johan (2004). "The Birth of Object Orientation: The Simula Languages" (PDF). From Object-Orientation to Formal Methods. Lecture Notes in Computer Science. 2635. pp. 15–25. CiteSeerX 10.1.1.133.6730. doi:10.1007/978-3-540-39993-3_3. ISBN 978-3-540-21366-6. Retrieved 3 March 2018.
  18. ^ a b Bertrand Meyer (2009). Touch of Class: Learning to Program Well with Objects and Contracts. Springer Science & Business Media. p. 329. Bibcode:2009tclp.book.....M. ISBN 978-3-540-92144-8.
  19. ^ Kay, Alan. "The Early History of Smalltalk". Archived from the original on 10 July 2008. Retrieved 13 September 2007.
  20. ^ 1995 (June) Visual FoxPro 3.0, FoxPro evolves from a procedural language to an object-oriented language. Visual FoxPro 3.0 introduces a database container, seamless client/server capabilities, support for ActiveX technologies, and OLE Automation and null support. Summary of Fox releases
  21. ^ FoxPro History web site: Foxprohistory.org
  22. ^ 1995 Reviewers Guide to Visual FoxPro 3.0: DFpug.de
  23. ^ Khurana, Rohit (1 November 2009). Object Oriented Programming with C++, 1E. ISBN 978-81-259-2532-3.
  24. ^ "The Emerald Programming Language". 26 February 2011.
  25. ^ Neward, Ted (26 June 2006). "The Vietnam of Computer Science". Interoperability Happens. Archived from the original on 4 July 2006. Retrieved 2 June 2010.
  26. ^ Meyer, Second Edition, p. 230
  27. ^ M.Trofimov, OOOP – The Third "O" Solution: Open OOP. First Class, OMG, 1993, Vol. 3, issue 3, p.14.
  28. ^ Wirth, Nicklaus (2006). "Good Ideas, Through the Looking Glass" (PDF). Computer. 39 (1): 28–39. doi:10.1109/mc.2006.20. Archived from the original (PDF) on 12 October 2016. Retrieved 2 October 2016.
  29. ^ Yegge, Steve (30 March 2006). "Execution in the Kingdom of Nouns". steve-yegge.blogspot.com. Retrieved 3 July 2010.
  30. ^ Boronczyk, Timothy (11 June 2009). "What's Wrong with OOP". zaemis.blogspot.com. Retrieved 3 July 2010.
  31. ^ Ambler, Scott (1 January 1998). "A Realistic Look at Object-Oriented Reuse". drdobbs.com. Retrieved 4 July 2010.
  32. ^ Shelly, Asaf (22 August 2008). "Flaws of Object Oriented Modeling". Intel Software Network. Retrieved 4 July 2010.
  33. ^ James, Justin (1 October 2007). "Multithreading is a verb not a noun". techrepublic.com. Archived from the original on 10 October 2007. Retrieved 4 July 2010.
  34. ^ Shelly, Asaf (22 August 2008). "HOW TO: Multicore Programming (Multiprocessing) Visual C++ Class Design Guidelines, Member Functions". support.microsoft.com. Retrieved 4 July 2010.
  35. ^ Robert Harper (17 April 2011). "Some thoughts on teaching FP". Existential Type Blog. Retrieved 5 December 2011.
  36. ^ a b Cardelli, Luca (1996). "Bad Engineering Properties of Object-Oriented Languages". ACM Comput. Surv. 28 (4es): 150–es. doi:10.1145/242224.242415. ISSN 0360-0300. Retrieved 21 April 2010.
  37. ^ a b Armstrong, Joe. In Coders at Work: Reflections on the Craft of Programming. Peter Seibel, ed. Codersatwork.com Archived 5 March 2010 at the Wayback Machine, Accessed 13 November 2009.
  38. ^ a b Stepanov, Alexander. "STLport: An Interview with A. Stepanov". Retrieved 21 April 2010.
  39. ^ a b Rich Hickey, JVM Languages Summit 2009 keynote, Are We There Yet? November 2009.
  40. ^ Potok, Thomas; Mladen Vouk; Andy Rindos (1999). "Productivity Analysis of Object-Oriented Software Developed in a Commercial Environment" (PDF). Software – Practice and Experience. 29 (10): 833–847. doi:10.1002/(SICI)1097-024X(199908)29:10<833::AID-SPE258>3.0.CO;2-P. Retrieved 21 April 2010.
  41. ^ C. J. Date, Introduction to Database Systems, 6th-ed., Page 650
  42. ^ C. J. Date, Hugh Darwen. Foundation for Future Database Systems: The Third Manifesto (2nd Edition)
  43. ^ Krubner, Lawrence. "Object Oriented Programming is an expensive disaster which must end". smashcompany.com. Archived from the original on 14 October 2014. Retrieved 14 October 2014.
  44. ^ Graham, Paul. "Why ARC isn't especially Object-Oriented". PaulGraham.com. Retrieved 13 November 2009.
  45. ^ Brodie, Leo (1984). Thinking Forth (PDF). pp. 92–93. Retrieved 4 May 2018.
  46. ^ Hunt, Andrew. "Don't Repeat Yourself". Category Extreme Programming. Retrieved 4 May 2018.
  47. ^ "Stevey's Blog Rants: Execution in the Kingdom of Nouns". Retrieved 20 May 2020.
  48. ^ a b Eric S. Raymond (2003). "The Art of Unix Programming: Unix and Object-Oriented Languages". Retrieved 6 August 2014.
  49. ^ Pike, Rob (2 March 2004). "[9fans] Re: Threads: Sewing badges of honor onto a Kernel". comp.os.plan9 (Mailing list). Retrieved 17 November 2016.
  50. ^ Pike, Rob (25 June 2012). "Less is exponentially more". Retrieved 1 October 2016.
  51. ^ Pike, Rob (14 November 2012). "A few years ago I saw this page". Archived from the original on 14 August 2018. Retrieved 1 October 2016.
  52. ^ Poll, Erik. "Subtyping and Inheritance for Categorical Datatypes" (PDF). Retrieved 5 June 2011.
  53. ^ a b Abadi, Martin; Cardelli, Luca (1996). A Theory of Objects. Springer-Verlag New York, Inc. ISBN 978-0-387-94775-4. Retrieved 21 April 2010.

Further reading[edit]

  • Abadi, Martin; Luca Cardelli (1998). A Theory of Objects. Springer Verlag. ISBN 978-0-387-94775-4.
  • Abelson, Harold; Gerald Jay Sussman (1997). Structure and Interpretation of Computer Programs. MIT Press. ISBN 978-0-262-01153-2.
  • Armstrong, Deborah J. (February 2006). "The Quarks of Object-Oriented Development". Communications of the ACM. 49 (2): 123–128. doi:10.1145/1113034.1113040. ISSN 0001-0782.
  • Booch, Grady (1997). Object-Oriented Analysis and Design with Applications. Addison-Wesley. ISBN 978-0-8053-5340-2.
  • Eeles, Peter; Oliver Sims (1998). Building Business Objects. John Wiley & Sons. ISBN 978-0-471-19176-6.
  • Gamma, Erich; Richard Helm; Ralph Johnson; John Vlissides (1995). Design Patterns: Elements of Reusable Object Oriented Software. Addison-Wesley. Bibcode:1995dper.book.....G. ISBN 978-0-201-63361-0.
  • Harmon, Paul; William Morrissey (1996). The Object Technology Casebook – Lessons from Award-Winning Business Applications. John Wiley & Sons. ISBN 978-0-471-14717-6.
  • Jacobson, Ivar (1992). Object-Oriented Software Engineering: A Use Case-Driven Approach. Addison-Wesley. Bibcode:1992oose.book.....J. ISBN 978-0-201-54435-0.
  • Kay, Alan. The Early History of Smalltalk. Archived from the original on 4 April 2005. Retrieved 18 April 2005.
  • Meyer, Bertrand (1997). Object-Oriented Software Construction. Prentice Hall. ISBN 978-0-13-629155-8.
  • Pecinovsky, Rudolf (2013). OOP – Learn Object Oriented Thinking & Programming. Bruckner Publishing. ISBN 978-80-904661-8-0.
  • Rumbaugh, James; Michael Blaha; William Premerlani; Frederick Eddy; William Lorensen (1991). Object-Oriented Modeling and Design. Prentice Hall. ISBN 978-0-13-629841-0.
  • Schach, Stephen (2006). Object-Oriented and Classical Software Engineering, Seventh Edition. McGraw-Hill. ISBN 978-0-07-319126-3.
  • Schreiner, Axel-Tobias (1993). Object oriented programming with ANSI-C. Hanser. hdl:1850/8544. ISBN 978-3-446-17426-9.
  • Taylor, David A. (1992). Object-Oriented Information Systems – Planning and Implementation. John Wiley & Sons. ISBN 978-0-471-54364-0.
  • Weisfeld, Matt (2009). The Object-Oriented Thought Process, Third Edition. Addison-Wesley. ISBN 978-0-672-33016-2.
  • West, David (2004). Object Thinking (Developer Reference). Microsoft Press. ISBN 978-0-7356-1965-4.

External links[edit]

  • Object-oriented programming at Curlie
  • Introduction to Object Oriented Programming Concepts (OOP) and More by L.W.C. Nirosh
  • Discussion about the flaws of OOD
  • OOP Concepts (Java Tutorials)
  • Science or Snake Oil: Empirical Software engineering Thoughts on software and systems engineering, by Ian Sommerville (2011-8-29)