You get a bonus - 1 coin for daily activity. Now you have 1 coin

1 Object-oriented approach to software development 1.1 The concepts of object and class

Lecture



Object-oriented programming (OOP) should be understood as an implementation methodology, in which a program is organized as a set of cooperating objects, each of which is an instance of a class, and the classes form an inheritance hierarchy. In this case, classes are usually static, and objects are very dynamic, which is encouraged by dynamic linking and polymorphism (for now, do not pay attention to the fact that most of the words in this definition are not clear to you). Although, under OOP, only what has been written above should be understood, it is often understood as an object-oriented approach to software creation. The latter along with OOP includes object-oriented analysis (object-oriented analisys, OOA) and object-oriented design (object-oriented design). All these concepts are closely related to the concepts of an object, a class, and an object model.

1.1 The concepts of object and class

1.1.1 Nature of objects

An object is something that can be operated on. The object has a state, behavior and identity. The structure and behavior of similar objects are defined in a class common to them. The terms "instance" and "object" are interchangeable.

A class is a set of objects with a common structure and behavior.

You all know such concepts as type and variable. Based on this, we can say that a class is the same as a type, and an object is the same as a variable. You are used to the fact that the int type means an integer number, float - a number with a floating comma, etc. Now we will try to expand this set a little. Imagine that there is such a type as a person. The variable in this case will be a specific person, for example, I, or any of you. Similarly, we can introduce a class table whose objects will be this table and that table.

Now in more detail we will deal with the definition of the object. Namely, with the concepts of state, behavior and identity.

condition

The state of an object is characterized by a list (usually static) of all properties of a given object and the current (usually dynamic) values ​​of each of these properties. As an example, consider the machine that sells coffee. One of the properties is the number of coins stored in it. The fact that this property always exists determines the static. The value of this property determines the dynamics.

Behavior

Behavior is how an object acts and reacts; behavior is expressed in terms of the state of the object and the transfer of messages. In other words, the object's behavior is its observed and externally verifiable activity.

The operation is defined as the influence of one object on another in order to cause a corresponding reaction.

On the one hand, the behavior of an object changes its state. On the other - the behavior depends on the state. Indeed, consider the behavior of the automaton. On the one hand, one of the parts of his behavior is to accept a coin. This part of the behavior affects the part of the state – the number of coins. On the other - it is part of the state - the number of coins determines to some extent the behavior of the machine. Namely, whether to pour coffee into a glass or not. Thus, it can be concluded that the state of an object represents the total result of its behavior.

The behavior of an object is constructed from its operations. There are three types of operations

  • Modifier - an operation that changes the state of an object
  • A selector is an operation that reads the state of an object but does not change its state.
  • Iterator is an operation that allows you to organize access to all parts of an object in a strictly defined sequence.

Identity

Identity is a property of an object or a set of properties that distinguishes it from all other objects. For example, when we program, we can uniquely identify an object by its name. The object stored in the database, we can determine by a set of properties that define the primary key.

1.1.2 Relationships Between Objects

Objects in themselves are of no interest: only in the process of interaction of objects is the system implemented. As Ingals puts it: "Instead of a processor shamelessly grinding a data structure, we get a community of well-mannered objects who politely ask each other for services." The plane, by definition, "a collection of elements, each of which by its nature tends to fall to the ground, but at the expense of joint continuous efforts to overcome this trend." It flies only thanks to the concerted efforts of its components.

The relationship of any two objects is based on the assumptions one possesses with respect to the other: about the operations that can be performed and the expected behavior. Of particular interest for object-oriented analysis and design are two types of hierarchical relationships of objects: communication and aggregation.

Relationship type "relationship"

We borrow the concept of communication from Rumbaugh (Rumbaugh), which defines it as a “physical or conceptual connection between objects”. The object cooperates with other objects through connections connecting it with them. In other words, a connection is a specific mapping through which a client requests a service from a server object or through which one object finds a path to another.

When participating in a relationship, an entity can perform one of the following three roles:

  • Actor . Actor is a doer, performer. The object may affect other objects, but it itself is never exposed to other objects; in a sense, this corresponds to the concept of an active object.
  • Server An object can only be affected by other objects, but it never acts as an affecting object.
  • Agent Such an object can act both in an active and in a passive role; As a rule, an agent object is created to perform operations in the interests of an actor or agent object.

An example of a relationship “connection” is the relationship between the objects “pilot” and “dispatcher”. The pilot may request the dispatcher for different data on the course, height, level, glide slope, etc.

In conclusion, we can say that if client-server relations exist between two objects, then they most often are in relation to the type of connection.

Attitudes like “aggregation”

While relationships designate peer or "client-server" relationships between objects, aggregation describes the relationship of the whole and the parts leading to the corresponding hierarchy of objects, and, coming from the whole (aggregate), we can come to its parts (attributes). In this sense, aggregation is a specialized special case of association.

Aggregation may mean the physical entry of one object into another, but not necessarily. The aircraft consists of wings, engines, landing gear and other parts. On the other hand, a shareholder's relationship with his shares is an aggregation that does not provide for physical inclusion. The shareholder holds his shares exclusively, but they are not physically included. This is undoubtedly an aggregation relation, but more conceptual than physical in nature.

Choosing one of two things — linkage or aggregation — one has to keep in mind the following. Aggregation is sometimes preferable because it allows you to hide parts in general. Sometimes the opposite is preferable to communication, because they are weaker and less restrictive. Making a decision, you have to weigh everything.

An object that is an attribute of another object (aggregate) has a connection with its aggregate. Through this connection, the unit can send messages to it.

Most object notations introduce the concept of an object diagram. An object diagram is part of the object-oriented design notation; used to visually show objects and the relationships between them in the logical design of the system. May reflect all or part of the object structure; usually illustrates the meaning of mechanisms in a logical design. A separate diagram of objects - a snapshot of the life of the system. Often, an object diagram is called a collaboration diagram. The main symbols on this diagram are as follows:

1 Object-oriented approach to software development 1.1 The concepts of object and class

Figure 1.1 Object Designation

1 Object-oriented approach to software development 1.1 The concepts of object and class

Figure 1.2 Relationship type "relationship"

In addition to collaboration diagrams, there is another type of object diagrams - sequence diagrams. Sequence diagrams serve the same purposes as collaboration diagrams.

The relation “aggregation” type between objects does not have a special designation. The point is that the relation “aggregation” between objects corresponds to the relation “aggregation” between their classes. For aggregation between classes there is a special designation, but we'll talk about it a little later.

1.1.3 Nature of classes

The concepts of a class and an object are so closely related that it is impossible to speak about an object without reference to its class. However, there is an important distinction between these two concepts. While an object denotes a specific entity, defined in time and in space, a class defines only an abstraction of the essential in the object. Thus, we can speak of the class "Mammals", which includes characteristics common to all mammals. In order to point to a specific mammalian representative, it is necessary to say “this is a mammal” or “that is a mammal”.

Let me remind you that the class represents a set of objects that have a common structure and the same behavior.

Any particular object is just an instance of a class. What is not a class? The object is not a class, although later we will see that a class can be an object. Objects that are not connected by a common structure and behavior cannot be combined into a class, since by definition they are not interconnected by anything other than the fact that they are all objects.

It is important to note that classes, as they are understood in most existing programming languages, are necessary, but not sufficient, for decomposing complex systems. Some abstractions are so complex that they cannot be expressed in terms of a simple class definition. For example, at a fairly high level of abstraction, a graphical user interface, database, or accounting system as a whole, these are explicit objects, but not instances of classes. It is better to consider them as certain sets of cooperating classes. Stroustrup calls such clusters components. We will use either this concept or its equivalent category of classes.

1.1.4 Relationship between classes

In total between classes there are 6 types of relations: association, inheritance, aggregation, use, instantiation and metaclass.

Before we consider the listed relations in detail, we introduce several definitions and notation. And so, classes and their relationships are most often represented on the class diagram. The class diagram is part of the object-oriented designation system; used to visually show classes and their relationships in the logical design of the system. It can represent the whole structure of classes or its part. On class diagrams, a class is represented as follows:

1 Object-oriented approach to software development 1.1 The concepts of object and class

Figure 1.3 Class Designation

Now consider each relationship in more detail.

Association

Let's start with an example. Wanting to automate a retail outlet, we find two abstractions - products and sales. In fig. 1.4 shows the association that we see. The Product class is what we sold in a certain transaction, and the Sale class is the transaction itself, in which several goods are sold. Probably, the association works in both directions: having set the product, you can enter into the transaction in which it was sold, and, having gone from the transaction, you can find what was sold.

1 Object-oriented approach to software development 1.1 The concepts of object and class

Figure 1.4 Association designation

As this example shows, association is a semantic connection. By default, it has no direction (unless otherwise stated, association, as in this example, implies two-way communication) and does not explain how classes communicate with each other (we can only mark semantic dependence, indicating which roles classes play for each friend). However, this is what we need at an early stage of analysis. If it is necessary to clearly indicate the direction of the association, this can be done by drawing an arrow.

So, we fix the participants, their roles and (as will be discussed later) the power of the relationship.

Power . In the previous example, we had a one-to-many association. Thus, we designated its power (that is, roughly speaking, the number of participants). In practice, it is important to distinguish between three cases of association power: one-to-one, one-to-many, and many-to-many.

Inheritance

Inheritance is a relationship between classes in which a class uses the structure or behavior of another (single inheritance) or other (multiple inheritance) classes. Inheritance introduces a common / partial hierarchy in which the subclass inherits from one or more of the more general superclasses. Subclasses usually complement or override the inherited structure and behavior.

In class diagrams, inheritance is indicated as follows:

1 Object-oriented approach to software development 1.1 The concepts of object and class

Figure 1.5 Designation of Inheritance

Child classes typically extend the structure and / or behavior of the parent class. A child class is often called a subclass, the parent class is called a superclass. Naturally, the inheritance hierarchy can be built from more than two levels, although more than seven levels are used very rarely. This is due to the fact that it is difficult for a person to perceive a hierarchy consisting of more than seven levels. The highest class in the inheritance hierarchy is called the base class.

Most often, in real systems, we create objects of only those classes that are at the lowest levels of the inheritance hierarchy. This is due to the fact that classes at higher levels often contain only the interface of a certain abstraction, but not its implementation. Classes that contain only an interface are called abstract. A class is abstract even if it does not have at least one of the declared operations implemented. Classes in which all declared operations are implemented are called concrete. We can create objects of specific classes only.

A class usually has two kinds of clients:

  • copies;
  • subclasses.

It is often useful to have different interfaces for them. In particular, we want to show only externally visible behavior for client instances, but we need to open service functions and views to client subclasses. This explains the presence of an open, protected and closed part of the class description in the C ++ language: the developer can clearly distinguish which elements of the class are available.

There are serious contradictions between the needs of inheritance and encapsulation. To a large extent, inheritance opens up some secrets to the inheriting class. In practice, to understand how a class works, it is often necessary to examine all its superclasses in their internal details.

Multiple inheritance

We considered issues related to single inheritance, that is, when a subclass has exactly one superclass. However, single inheritance, for all its utility, often forces a programmer to choose between two equally attractive classes. This limits the ability to reuse certain classes and makes duplicate existing codes. For example, you cannot inherit a graphic element that would be both a circle and a picture; you have to inherit one thing and add the necessary from the second.

Multiple inheritance is directly supported in C ++ and CLOS, as well as, to some extent, in Smalltalk. The need for multiple inheritance in OOP remains a subject of heated debate. In our experience, multiple inheritance is like a parachute: as a rule, it is not needed, but when it is suddenly needed, it will be a pity if it is not at hand.

Imagine that we need to organize accounting for various types of tangible and intangible property - bank accounts, real estate, stocks and bonds. Bank accounts are current and savings. Stocks and bonds can be classified as securities, their management is completely different from bank accounts, but accounts and securities are types of property.

However, there are many other useful classifications of the same types of property. In some context, it may be necessary to distinguish between what can be insured (real estate and, to some extent, savings deposits). Another aspect is the ability of the property to pay dividends; this is a common property of bank accounts and securities.

Obviously, single inheritance in this case does not reflect reality, so it is necessary to resort to multiple ones. In fact, it is a litmus test for multiple inheritance. Если мы составим структуру классов, в которой конечные классы (листья) могут быть сгруппированы в множества по разным ортогональным признакам (как в нашем примере, где такими признаками были способность приносить дивиденды и возможность страховки) и эти множества перекрываются, то это служит признаком невозможности обойтись одной структурой наследования, в которой бы существовали какие-то промежуточные классы с нужным поведением. Мы можем исправить ситуацию, используя множественное наследование, чтобы соединить два нужных поведения там, где это необходимо. В этом случае класс “Ценные бумаги” будет наследовать от классов “Источник дивидендов” и “Имущество”

Агрегация

Aggregation between classes has similar semantics with aggregation between objects. Inter-class aggregation means that instances of one class include instances of another class. Just like objects, aggregation between a class can be logical or physical (composition). Consider examples.

1 Object-oriented approach to software development 1.1 The concepts of object and class

Figure 1.6 Logical aggregation

1 Object-oriented approach to software development 1.1 The concepts of object and class

Figure 1.7. Physical aggregation (composition)

Instantiation

We introduce the definition of a generic class. By a generic class, we mean a class that serves as a template for creating other classes: the template is parameterized by other classes, objects, and / or operations. The generic class must be instantiated before creating objects. Generic classes are used as container classes. The terms "generic class" and "parameterized class" are used interchangeably.

Instantiation - substitution of template parameters of a generalized or parameterized class; As a result, a specific class is created that can have instances.

Metaclass

As mentioned, any object is an instance of a class. What happens if we try and treat the classes themselves as objects? For this we need to answer the question, what is a class of a class? The answer is a metaclass. In other words, a metaclass is a class whose instances are classes. Metaclasses crown the object model in pure object-oriented languages. Accordingly, they are in Smalltalk and CLOS, but not in C ++.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Object oriented programming

Terms: Object oriented programming