Article de reference

Object-oriented programming

UML notation for a class. This Button class has variables for data, and functions . Through inheritance, a subclass can be created as a subset of the Button class. Objects are i...

UML notation for a class. This Button class has variables for data, and functions. Through inheritance, a subclass can be created as a subset of the Button class. Objects are instances of a class.

Object-oriented programming (OOP) is a programming paradigm based on objectssoftware entities that encapsulatedata and function(s).computer program consists of objects that interact with one another. An OOP language is one that provides object-oriented programming features, but as the set of features that contribute to OOP is contested, classifying a language as OOP – and the degree to which it supports OOP – is debatable. As paradigms are not mutually exclusive, a language can be multi-paradigm (i.e. categorized as more than only OOP).

Notable languages with OOP support include Ada, ActionScript, C++, Common Lisp, C#, Dart, Eiffel, Fortran 2003, Haxe, Java,JavaScript, Kotlin, Logo, MATLAB, Objective-C, Object Pascal, Perl, PHP, Python, R, Raku, Ruby, Scala, SIMSCRIPT, Simula, Smalltalk, Swift, Vala and Visual Basic (.NET).

d'intelligence artificielle du Massachusetts Institute of Technology (MIT) à la fin des années 1950 et au début des années 1960. À cette époque, le terme « objet » désignait des atomes LISP dotés de propriétés (attributs) identifiées. Un autre exemple précoce est Sketchpad, créé par Ivan Sutherland au MIT entre 1960 et 1961. Dans le glossaire de son rapport technique, Sutherland définissait des termes tels que « objet » et « instance » (le concept de classe étant couvert par les termes « maître » ou « définition »), bien que cette définition fût spécialisée dans l'interaction graphique. Plus tard, en 1968, AED-0, la version du MIT du langage de programmation ALGOL , associait les structures de données (« plexes ») et les procédures, préfigurant ce qui allait devenir les « messages », les « méthodes » et les « fonctions membres ». Des sujets tels que l'abstraction des données et la programmation modulaire étaient fréquemment abordés à cette époque.

Parallèlement, en Norvège, Simula a été développé entre 1961 et 1967. Simula a introduit des concepts essentiels de la programmation orientée objet, tels que les classes , l'héritage et la liaison dynamique . Simula était principalement utilisé par les chercheurs travaillant sur la modélisation physique , notamment le mouvement des navires et de leur cargaison dans les ports de marchandises. Simula est généralement considéré comme le premier langage possédant les caractéristiques et le cadre fondamentaux d'un langage orienté objet.

J'imaginais les objets comme des cellules biologiques et/ou des ordinateurs individuels sur un réseau, capables de communiquer uniquement par messages (la messagerie est donc apparue dès le début – il a fallu un certain temps pour trouver comment implémenter la messagerie dans un langage de programmation de manière suffisamment efficace pour être utile).

— Alan Kay,

Influencé par le MIT et Simula, Alan Kay commença à développer ses propres idées en novembre 1966. Il créera par la suite Smalltalk , un langage de programmation orientée objet (POO) influent. Dès 1967, Kay utilisait couramment le terme « programmation orientée objet » . Bien que parfois considéré comme le « père » de la POO Kay a déclaré que ses idées différaient de la compréhension commune de la POO et a laissé entendre que la communauté informatique n'avait pas adopté sa conception . Une note du MIT de 1976, co-écrite par Barbara Liskov, cite Simula 67 , CLU et Alphard parmi les langages orientés objet, mais ne mentionne pas Smalltalk

Dans les années 1970, la première version du langage de programmation Smalltalk a été développée au Xerox PARC par Alan Kay , Dan Ingalls et Adele Goldberg . Smalltalk-72 se distinguait par son utilisation d'objets au niveau du langage et par son environnement de développement graphique. Smalltalk était un système entièrement dynamique, permettant aux utilisateurs de créer et de modifier des classes en temps réel. Une grande partie de la théorie de la programmation orientée objet (POO) a été développée dans le contexte de Smalltalk, notamment l'héritage multiple.

In the late 1970s and 1980s, OOP rose to prominence. The Flavors object-oriented Lisp was developed starting 1979, introducing multiple inheritance and mixins. In August 1981, Byte Magazine highlighted Smalltalk and OOP, introducing these ideas to a wide audience. LOOPS, the object system for Interlisp-D, was influenced by Smalltalk and Flavors, and a paper about it was published in 1982. In 1986, the first Conference on Object-Oriented Programming, Systems, Languages, and Applications (OOPSLA) was attended by 1,000 people. This conference marked the start of efforts to consolidate Lisp object systems, eventually resulting in the Common Lisp Object System. 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 SmartRekursiv.

In the mid-1980s, new object-oriented languages like Objective-C, C++, and the Eiffel language emerged. Objective-C was developed by Brad Cox, who had used Smalltalk at ITT Inc.Bjarne Stroustrup created C++ based on his experience using Simula for his PhD thesis.Bertrand Meyer produced the first design of the Eiffel language in 1985, which focused on software quality using a design by contract approach.

In the 1990s, OOP became the main way of programming, especially as more languages supported it. These included Visual FoxPro 3.0,C++, and Delphigraphical user interfaces, which used objects for buttons, menus and other elements. One well-known example is Apple's Cocoa framework, used on macOS and written in Objective-C. OOP toolkits also enhanced the popularity of event-driven programming.ETH Zürich, Niklaus Wirth and his colleagues created new approaches to OOP. Modula-2 (1978) and Oberon (1987), included a distinctive approach to object orientation, classes, and type checking across module boundaries. Inheritance is not obvious in Wirth's design since his nomenclature looks in the opposite direction: It is called type extension and the viewpoint is from the parent down to the inheritor.

Many programming languages that were initially developed before OOP was popular have been augmented with object-oriented features, including Ada, BASIC, Fortran, Pascal, and COBOL.

Features

relational programming, is difficult because there isn't a clear, agreed-upon definition of OOP.

Encapsulation and information hiding

Information hiding and encapsulation can refer to several related concepts:

  • Cohesion, keeping related fields and methods together. A field (a.k.a. attribute or property) contains information (a.k.a. state) as a variable. A method (a.k.a. function or action) defines behavior via logic code.
  • Decoupling, organizing code so that only certain parts of the data are used by related functions. Decoupling makes it easier to change how an object works on the inside without affecting other parts of the codebase, such as in code refactoring. Objects act as a boundary between their internal workings and external, consuming code.
  • Data hiding, keeping the internal details of an object hidden from outside code. Consuming code can only interact with an object via its public members, due to the language providing access modifiers that control visibility.

Certains langages de programmation, comme Java, permettent de masquer les informations via des mots clés de visibilité (`private` Eric S. Raymond a écrit que les langages POO tendent à encourager des programmes à forte structure en couches qui nuisent à la transparence. Raymond compare défavorablement cette approche à celle adoptée avec Unix et le langage C.

SOLID inclut le principe ouvert/fermé , selon lequel les classes et les fonctions doivent être « ouvertes à l’extension, mais fermées à la modification ». Luca Cardelli a déclaré que les langages orientés objet ont des « propriétés de modularité extrêmement faibles en ce qui concerne l’extension et la modification des classes » et ont tendance à être extrêmement complexes. Ce dernier point est réitéré par Joe Armstrong , le principal inventeur d’ Erlang , qui aurait déclaré :

Le problème des langages orientés objet, c'est qu'ils traînent avec eux tout un environnement implicite. Vous vouliez une banane, mais vous vous êtes retrouvé avec un gorille tenant la banane et toute la jungle.

Leo Brodie affirme que la dissimulation d'informations peut conduire à du code dupliqué , ce qui va à l'encontre de la règle « ne vous répétez pas » du développement logiciel.

Héritage

L'héritage peut être pris en charge via la classe ou le prototype , qui présentent des différences mais utilisent des termes similaires comme objet et instance .

Basé sur les classes

En programmation orientée objet ( POO), le type le plus courant, un objet est une instance d'une classe. La classe définit les données (variables) et les méthodes (logique). Un objet est créé via le constructeur . Chaque instance de la classe possède le même ensemble de variables et de méthodes. Les éléments peuvent inclure :

  • Variable de classe – appartient à la classe elle-même ; tous les objets de la classe partagent une seule copie.
  • Variable d'instance – appartient à un objet ; chaque objet possède sa propre version de ces variables.
  • Variable membre – désigne à la fois les variables de classe et les variables d'instance d'une classe
  • Méthode de classe – ne peut utiliser que des variables de classe
  • Méthode d'instance – appartient à un objet ; peut utiliser des variables d'instance et de classe

Les classes peuvent hériter d'autres classes, créant ainsi une hiérarchie : une sous-classe héritant d'une super-classe. Par exemple, une l'héritage multiple , où une classe peut hériter de plusieurs classes, et d'autres prennent en charge les mixins ou les traits . Par exemple, un mixin appelé UnicodeConversionMixin peut ajouter une méthode unicode_to_ascii() aux classes FileReader et WebPageScraper.

Une classe abstraite ne peut pas être instanciée directement en tant qu'objet. Elle est uniquement utilisée comme super-classe.

D'autres classes sont des classes utilitaires qui ne contiennent que des variables et des méthodes de classe et ne sont pas destinées à être instanciées ou sous-classées.

Basé sur un prototype

Au lieu de proposer un concept de classe, la programmation par prototypes associe un objet à un autre objet, appelé son prototype ou parent . En `Self`, un objet peut avoir plusieurs parents ou aucun , mais en JavaScript , le langage par prototypes le plus répandu, un objet possède exactement un lien de prototype, jusqu'à l'objet de base dont le prototype est nul.

Un prototype sert de modèle pour les nouveaux objets. Par exemple, si vous avez un objet A object composition, an object can contain other objects. For example, an Go, don't support inheritance. Instead, they encourage "composition over inheritance", where objects are built using smaller parts instead of parent-child relationships. For example, instead of inheriting from class Person, the Employee class could simply contain a Person object. This lets the Employee class control how much of Person it exposes to other parts of the program. Delegation is another language feature that can be used as an alternative to inheritance.

Programmers have different opinions on inheritance. Bjarne Stroustrup, author of C++, has stated that it is possible to do OOP without inheritance.Rob Pike has criticized inheritance for creating complex hierarchies instead of simpler solutions.

Inheritance and behavioral subtyping

People often think that if one class inherits from another, it means the subclass "is a" more specific version of the original class. This presumes the program semantics are that objects from the subclass can always replace objects from the original class without problems. This concept is known as behavioral subtyping, more specifically the Liskov substitution principle.

However, this is often not true, especially in programming languages that allow mutable objects, objects that change after they are created. In fact, subtype polymorphism as enforced by the type checker in OOP languages cannot guarantee behavioral subtyping in most if not all contexts. For example, the circle-ellipse problem is notoriously difficult to handle using OOP's concept of inheritance. Behavioral subtyping is undecidable in general, so it cannot be easily implemented by a compiler. Because of this, programmers must carefully design class hierarchies to avoid mistakes that the programming language itself cannot catch.

Dynamic dispatch

A method may be invoked via dynamic dispatch such that the method is selected at runtime instead of compile time. If the method choice depends on more than one type of object (such as other objects passed as parameters), it's called multiple dispatch. In this context, a method call is also known as message passing, meaning the method name and its inputs are like a message sent to the object for it to act on.

Dynamic dispatch works together with inheritance: if an object doesn't have the requested method, it looks up to its parent class (delegation), and continues up the chain to find a matching method.

Polymorphism

Polymorphism in OOP refers to subtyping or subtype polymorphism, where a function can work with a specific interface and thus manipulate entities of different classes in a uniform manner.

For example, imagine a program has two shapes: a circle and a square. Both come from a common class called "Shape." Each shape has its own way of drawing itself. With subtype polymorphism, the program doesn't need to know the type of each shape, and can simply call the "Draw" method for each shape. The programming language runtime will ensure the correct version of the "Draw" method runs for each shape. Because the details of each shape are handled inside their own classes, this makes the code simpler and more organized, enabling strong separation of concerns.

Open recursion

An object's methods can access the object's data. Many programming languages use a special word, like open recursion, a method in an object can call other methods in the same object, including itself, using this special word. This allows a method in one class to call another method defined later in a subclass, a feature known as late binding.

Design patterns

Design patterns are common solutions to problems in software design. Some design patterns are especially useful for OOP, and design patterns are typically introduced in an OOP context.

Real-world modeling and relationships

Parfois, les objets représentent des éléments et des processus du monde réel sous forme numérique. Par exemple, un logiciel graphique peut comporter des objets tels que Niklaus Wirth a déclaré : « Ce paradigme [la POO] reflète fidèlement la structure des systèmes du monde réel et est donc bien adapté à la modélisation de systèmes complexes présentant un comportement complexe. »

Cependant, le plus souvent, les objets représentent des entités abstraites, comme un fichier ouvert ou un convertisseur d'unités. L'idée que la programmation orientée objet (POO) facilite la reproduction exacte du monde réel, voire même sa nécessité, ne fait pas l'unanimité. Bob Martin suggère que, les classes étant des logiciels, leurs relations ne correspondent pas aux relations du monde réel qu'elles représentent. Bertrand Meyer soutient qu'un programme n'est pas un modèle du monde, mais un modèle d'une partie du monde : « La réalité est une cousine éloignée. » Steve Yegge a constaté que les langages naturels ne suivent pas l'approche POO consistant à nommer une chose (objet) avant une action (méthode), contrairement à la programmation fonctionnelle qui procède inversement. Cela peut rendre une solution POO plus complexe qu'une solution écrite par programmation procédurale .

Modèles d'objets

Voici quelques modèles de conception logicielle notables pour les objets OOP.

Un anti-modèle courant est celui de l' objet divin , un objet qui en sait ou en fait trop.

Modèles de conception du Gang des Quatre

Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. People often call them the "Gang of Four". The book talks about the strengths and weaknesses of OOP and explains 23 common ways to solve programming problems.

These solutions, called "design patterns," are grouped into three types:

Object-orientation and databases

relational database management systems (RDBMSs) are widely used in software today. However, relational databases don't store objects directly, which creates a challenge when using them together. This issue is called object-relational impedance mismatch.

To solve this problem, developers use different methods, but none of them are perfect. One of the most common solutions is object-relational mapping (ORM), which helps connect object-oriented programs to relational databases. Examples of ORM tools include Visual FoxPro, Java Data Objects, and Ruby on Rails ActiveRecord.

Some databases, called object databases, are designed to work with OOP. However, they have not been as popular or successful as relational databases.

Date and Darwen have proposed a theoretical foundation that uses OOP as a kind of customizable type system to support RDBMSs, but it forbids objects containing pointers to other objects.

Responsibility- vs. data-driven design

Dans la conception axée sur les responsabilités , les classes sont construites en fonction de leurs besoins et des informations qu'elles partagent, sous la forme d'un contrat. Cela diffère de la conception axée sur les données , où les classes sont construites en fonction des données qu'elles doivent stocker. Selon Wirfs-Brock et Wilkerson, les initiateurs de la conception axée sur les responsabilités, cette dernière est la meilleure approche.

directives SOLID et GRASP

SOLID est un ensemble de cinq règles pour concevoir de bons logiciels, créé par Michael Feathers :

GRASP (General Responsibility Assignment Software Patterns) est un autre ensemble de règles de conception logicielle, créé par Craig Larman , qui aide les développeurs à attribuer des responsabilités à différentes parties d'un programme :

  • Principe du créateur : permet aux classes de créer des objets qu’elles utilisent fréquemment.
  • Principe de l'expert en information : attribue des tâches aux classes disposant des informations nécessaires.
  • Principe de faible couplage : réduit les dépendances entre les classes pour améliorer la flexibilité et la maintenabilité.
  • Principe de forte cohésion : concevoir des classes avec une responsabilité unique et ciblée.
  • Principe du contrôleur : attribue les opérations système à des classes distinctes qui gèrent le flux et les interactions.
  • Polymorphisme : permet d’utiliser différentes classes via une interface commune, favorisant ainsi la flexibilité et la réutilisation.
  • Principe de Pure Fabrication : créer des classes d’assistance pour améliorer la conception, renforcer la cohésion et réduire le couplage.

sémantique formelle

Researchers have tried to formally define the semantics of OOP. Inheritance presents difficulties, particularly with the interactions between open recursion and encapsulated state. Researchers have used recursive types and co-algebraic data types to incorporate essential features of OOP. Abadi and Cardelli defined several extensions of System F<: that deal with mutable objects, allowing both subtype polymorphism and parametric polymorphism (generics), and were able to formally model many OOP concepts and constructs. Although far from trivial, static analysis of object-oriented programming languages such as Java is a mature field, with several commercial tools.

The TIOBE programming language popularity index graph from 2002 to 2023. In the 2000s the object-oriented Java (orange) and the proceduralC (dark blue) competed for the top position.

Many popular programming languages, like C++, Java, and Python, use OOP. In the past, OOP was widely accepted, but recently, some programmers have criticized it and prefer functional programming instead. A study by Potok et al. found no major difference in productivity between OOP and procedural programming.

Some believe that OOP places too much focus on using objects rather than on algorithms and data structures. For example, programmer Rob Pike pointed out that OOP can make programmers think more about type hierarchy than composition. He has called OOP "the Roman numerals of computing".Rich Hickey, creator of Clojure, described OOP as overly simplistic, especially when it comes to representing real-world things that change over time.Alexander Stepanov said that OOP tries to fit everything into a single type, which can be limiting. He argued that sometimes we need multisorted algebras: families of interfaces that span multiple types, such as in generic programming. Stepanov also said that calling everything an "object" doesn't add much understanding.

OOP was created to make code easier to reuse and maintain. However, it was not designed to clearly show the flow of a program's instructions. That was left to the compiler. As computers began using more parallel processing and multiple threads, it became more important to understand and control how instructions flow. This is difficult to do with OOP.

Paul Graham believes big companies like OOP because it helps manage large teams of average programmers. He argues that OOP adds structure, making it harder for one person to make serious mistakes, but at the same time restrains smart programmers.Eric S. Raymond, a Unix programmer and open-source software advocate, argues that OOP is not the best way to write programs.

Richard Feldman says that, while OOP features helped some languages stay organized, their popularity comes from other reasons. Lawrence Krubner argues that OOP doesn't offer special advantages compared to other styles, like functional programming, and can complicate coding.Luca Cardelli says that OOP is slower and takes longer to compile than procedural programming.

Plus d articles de Worldlex Wiki

Revenez a l index pour explorer davantage de pages sur l histoire, la science, la culture, la geographie et la societe en francais.

Explorer l index