Wednesday, November 20, 2013

TAW 12 - INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING

HISTORY OF SELECTED PROGRAMMING

ABAP was initially developed as an in-house programming language with reporting as the primary purpose. It was influenced by other programming languages such as PASCAL and COBOL. Over the period of time, the need to equip ABAP with several other functionalities was realized. This led to the introduction of concepts such as OOPS or Object Oriented Programming and Structure. Only those OOPS concepts, which had been successfully applied in developing other languages, such as C, C++, and Java were included. ABAP/4 was extended to form ABAP Objects. Hence, ABAP has evolved as a combination of both procedural and object-oriented elements.

CHARACTERISTIC OF THE PROSEDURAL PROGRAMMING MODEL

In a procedural programming model, data and the functions that work on the data are stored separately. Data is available in the form of global variables, while functions can be the subroutines. However, in this programming model, the access to global data is nonencapsulated. This means that any subprogram can access the global data. Therefore, data access is not consistent.

TYPICAL PROSEDURAL ABAP PROGRAM

The structure of a typical ABAP program begins with type definitions and data declarations, which provide information about the structure of data that the program will work on. The main program includes the functions which perform certain actions on that data. The main consists of your modularization unit calls, such as call of a subroutine or a function module call, followed by the corresponding definition of subroutines. The definition of a subroutine starts with the keyword FORM and ends with the keyword ENDFORM.

ENCAPSULATING DATA USING FUNCTION


When a function module is called in the program, the corresponding function group is loaded in the internal session. The function group remains active until the program execution is finished. Function modules of a function group can only be called from the main program. These have access to the global data of a function group. In other words, a main program cannot directly access the global data of a function group.
Thus, we can define a function group as a collection of data, and the functions that manage this data. Therefore, encapsulation – one of the many concepts of OOPS – is realized in procedural model with the help of function groups.


EXAMPLE OF A FUNCTION GROUP

Let us take the function group S_VEHICLE as an example. This function group contains services, such as inc_speed, dec_speed, and get_speed.
These services form the interface of the function group, and access the global data object, speed, which belongs to the whole function group.

The main program cannot access the function group’s data object speed directly.

SEVERAL INSTANCES OF ONE FUNCTION

If a main program requires several vehicles to work with, this would require extra programming effort. Most importantly, a specific vehicle cannot be represented by a whole function group.

MULTIPLE INSTATIATION IN OBJECT-ORIENTED PROGRAMMING


The example shown in this slide contains four vehicles with different characteristic instances. However, all these instances share the same data structure, range of functions, and have the ability to protect the data against access from outside. This suggests that one of the key characteristics of object-oriented programming is the creation of several runtime instances for a program context.

ABAP MAIN MEMORY AND ENCAPSULATION

Like Modularization units, which encapsulate the functions and work with the global data of the main program, object-oriented programming makes use of objects for encapsulating data and functions together. Multiple instantiation is supported. Like the function groups, the objects are also stored in the same internal session of the program. All data areas are separated from one another to ensure the data is protected.

DATA MANAGEMENT IN PROCEDURAL AND OBJECT - ORIENTED MODELS - SUMMARY

Unlike Procedural programming, object-oriented programming allows you to create a direct abstraction of a real object. This is possible with the help of multiple instantiation, the concept of which is systematically extended in the process.

ABAP OBJECT AS AN COMPATIBLE





ABAP differs from other object-oriented languages in the software development environment. The entire range of functions of the ABAP Workbench can be used with ABAP Objects. ABAP Objects statements can be used in procedural programs, and classes can contain procedural statements.
ABAP Objects is not a new language, but a systematic extension of ABAP. All the extensions including the procedural parts are upwardly compatible.
Type checks in ABAP Objects are stricter than in procedural context.
All obsolete statements are cleared in the ABAP Objects context. Therefore, the use of such statements may lead to syntax errors.

CLIENT/SERVER RELATIONSHIPS BETWEEN

In a generic way, a client can be defined as someone who procures certain services or asks for some services; while server is someone who provides those services. In an object-oriented model, objects can behave both as client or server depending on their role. In general, objects can perform both roles simultaneously: They can provide services to other objects while requesting services at the same time. In addition, the services are distributed amongst the objects in a manner which can avoid redundancies. This ensures that each object offers only those services that are within its area of responsibility.

ADDITIONAL CONCEPT OF THE OBJECT - ORIENTED PROGRAMMING MODEL




ABAP object-oriented programming model or ABAP Objects also includes features, such as Inheritance, Polymorphism, and Event controlling.
Inheritance defines the relationship between classes. It allows one class to not only adopt the structure or behavior of another class, but also to extend it.
Polymorphism is realized when instances of different classes respond differently to same messages.
Event controlling means that events are triggered by objects, if, at the time of development, it is not known how objects will react.

OBJECT-ORIENTED PROGRAMMING MODEL: CHARACTERISTICS


To summarize, ABAP Objects has these key characteristics:
  Objects are a direct abstraction of the real world.

  Objects are collections of data and the functions belonging to that data.

  Processes can be executed realistically.



OBJECT-ORIENTED PROGRAMMING MODEL: ADVANTAGES


The object-oriented programming model has various advantages:
  Better software structure and more consistency in development

  Reduced maintenance effort and lower incidence of errors

  Integration of the customer and the user into the analysis, design, and maintenance process

  Simpler and more secure software development process



THE SOFTWARE DEVELOPMENT PROCESS





The software development process is an iteration of four stages which constitute the whole development cycle:
  The first stage is requirement and idea.

  The second stage is analysis and design.

  The third stage is implementation.

  The final stage is testing. 


CLASSIFICATION ON OBJECTS



With object-oriented programming, the whole world can be realized as a collection of objects, for example a class of different cars, airplanes, and people. All those objects which exhibit similar characteristics and behavior can be grouped together in a class. Thus, a class can be defined as a collection of objects with similar characteristics and behavior. For example, lcl_vehicle is an object of a class ‘car’. This object is a concrete instance of a class.

CLASSES AS ABSTRACTION FORMS


In software development, abstractions are rudimentary models of the complex real world scenario. Consider a car as an example. Different people can have different perspectives about the same car.
A car enthusiast is specifically interested in properties like price, features, and color. Similarly, a scrap merchant pays particular attention to properties like weight, and scrap value. However, both these perspectives share some common features such as make, type, doors, wheels, and horse power. In software context, a car enthusiast and a scrap merchant can be considered as two different classes. Depending on the type of abstraction, a class can contain different aspects of an object.


COMPARISON OF CLASSES AND OBJECT




Let us put together the points to clearly understand the relationship between a Class and an Object.
Class gives the general description of objects.
It specifies status data or attributes and behavior or methods.
On the other hand, Object is a real time representation of the real world. It is a concrete form or specimen or instance of a class.

UML MODELING: DIAGRAM TYPES


Unified Modeling Language (or UML) is a globally standardized modeling language used for the specification, construction, visualization, and documentation of models for software systems. It enables uniform communication between users.
UML describes different diagram types to represent different views of a system. These three diagram types are of particular significance:
  Class diagrams represent the classes and the relationships between these in a static view of a model.

  Behavior diagrams describe the sequence in which the objects are related to each other.

  Component diagrams depict the organization and dependencies of components.



REPRETATION OF A CLASS




A class is represented by a rectangle in UML notation.
You first specify the name of the class, then its attributes, and finally its methods. However, you can either omit both the attribute part and the method part, or just one of the two.
Attributes define the data that can be stored in the objects of a class. They also determine the status of an object.
Methods define the functions that an object can perform.

EXAMPLE OF A CLASS DIAGRAM




A class diagram illustrates all static relationships between the classes as shown here. There are two basic types of static relationships:
  Association

  Generalization or Specialization

You can understand association relationship through an example where a customer books a car at a rental car company.
You can understand generalization or specialization relationship through an example where a car, a bus, and a truck are all vehicles.

ASSOSIATION




An association defines a semantic relationship between classes.
An association is represented by a line between the class symbols.
The cardinality, also referred to as multiplicity of the relationship, can be specified at each end of the line.
The cardinalities generally used are
  0…* which means any number;

  1 which means exactly one;

  1…* which means at least one; and

  0…1 which means at most one.

Arrows indicate the navigation options, that is, the accessibility of the association partner.
An association can have a name, and is written in italics above the line. It may contain an arrow to show the direction in which it is to be read.
Each association has two roles, one for each direction of the association.
If roles are defined for both partners, role names can be entered at the end of the lines. Each role has a cardinality that shows how many instances can participate in this relationship. The multiplicity or cardinality is the number of participating objects in one class that have a relationship to an object in the other class.
In this example, a cardinality of “at least one” indicates that, only a person who actually makes a booking becomes a customer of the rental car company.

ASSOCIATION WITH ROLES-EXMPLE




An example of multiple associations is shown here. lcl_person and lcl_company are two classes involved. Employee and employer are role names used at the end of the association lines. This gives a more detailed description of the relationships between the classes involved. A person can either appear in the role of ‘employee’ or ‘boss’ here.
Recursive association depicts two instances of the lcl_person class using role names: “child” and “parent”.


ASSOCIATION CLASSES



If association is used to link two classes, this relationship can be better represented by a special class. The various characteristics of the relationship are described using the attributes of the association class. A dotted line connects this additional class to the association line.

AGGREGATION AND COMPOSITION




Aggregation and composition are displayed as a line between two classes that is labeled with a small rhombus.
Aggregation is a special case of association, a whole-part relationship.
An empty rhombus is a symbol of aggregation.
Composition is a special case of aggregation, based on whole-part relationship. Composition means that the contained object cannot exist without the aggregate. Therefore, the cardinality of the aggregate can only be one.
In UML notation, composition is denoted by a filled-in rhombus.

GENERALIZATION AND SPECIALIZATION


Generalization and specialization are specific relationships that exist between classes. These are always bidirectional.
Generalization or specialization relationships are indicated by a triangular arrow. However, this arrow always points towards the more general class. The extent of generalization increases in the direction of the arrow.

OBJECT DIAGRAM


An object diagram illustrates the instances of the classes and the relationships between them. It can be defined as a variant of a class diagram which shows or depicts one section of the class diagram. It is useful for representing a complex class diagram.
In this example, an object diagram is represented as a “snapshot” of class diagram lcl_rental_booking with three instances Booking Car 1, Booking Car 2, and Booking Truck 1. All the three bookings here refer to a particular customer Mr. Smith of class lcl_customer. Attributes associated with the individual instances are also shown.

SEQUENCE DIAGRAM


Sequence diagrams are used to display certain processes or situations which are a part of the lifeline of the object. An object during its lifetime may create or delete objects or may exchange messages with other objects. Sequence diagrams focus on the time sequence of their behavior. In UML notation, the object lifeline is depicted by dotted vertical lines with a box containing the object name at the top. An ’X’ is placed at the point where the lifeline ends.
The control focus represented as a vertical rectangle on the object lifeline shows the object’s “active” period.
Messages are depicted as horizontal arrows between the object lines. The message is written above the arrow in the form of parameter as shown. The reply can be shown as a returning arrow.

DELEGATION PRINCIPLE IN A SEQUENCE DIAGRAM




Delegation involves two objects in a request handling process. The recipient of the request delegates the execution of the request to a delegate.
In this slide, the driver sends the message get_fuel_level to the car. When car receives this message, it sends a message to the tank to find out the tank details. In fact, the car delegates this task to the tank. If required, the car modifies the information containing the current value of the tank contents before it passes it back to the driver.


EXAMPLE OF A CLASS



This slide shows a vehicle as an example of a class. The name of the class is lcl_vehicle. The class lcl_vehicle consists of Public components, Private components, and methods for implementation. The public components are get_make and set_make. The private components are make and model. The keywords public and private describe the visibility or accessibility of the components in that section. Public components can be accessed outside the class. However, private attributes of the class are not accessible “from outside.”

DEFINING CLASSES


A class is a collection of objects that have similar structure and behavior. In other words, a class acts as a blueprint on which all objects in that class are created. You can define a class using the keyword ‘DEFINITION’. Generally, the syntax followed is CLASS class_name DEFINITION. Every class definition should end with keyword ENDCLASS.
All components of the class including attributes, methods, events, constants, and types are defined in the definition part.
A class also has an implementation part described by the keyword IMPLEMENTATION. Syntax is similar to that of definition part. Class implementation should also end with the keyword ENDCLASS. Only methods are implemented in the implementation part.

EXAMPLE OF ATTRIBUTE




This slide shows make as an example of attribute for the class lcl_vehicle. Attributes contain the data that can be stored in the objects of a class. Class attributes can be one of three types: elementary, structured, or table-type. They can consist of local or global data types or reference types.
Objects can be pointers to another object as shown.

DEFINITION OF ATTRIBUTES, TYPES, CONSTANTS




In the definition part of a class, you can define local data structures, constants, and data objects which can refer to local types or classes or interfaces.
Keyword TYPES is used to define the local data structures. Statement CONSTANTS is used within the class definition to describe data objects that have a constant value. You can refer to data types by only using the TYPE addition in DATA statements in classes. Similarly, the LIKE addition can only be used to define local data objects or SY fields, for example SY-DATE and SY-UNAME. The READ-ONLY addition indicates that, while a public attribute declared with DATA can be read from outside, it can only be changed by methods in the same class.
You can type an attribute as a reference with TYPE REF TO.


VISIBILITY SECTIONS OF ATTRIBUTES



Public and Private visibility sections define whether an attribute can be accessed outside the class or not. Public attributes of a class are generally visible and changeable. However, the read-only addition is an exception to this.
Private attributes, on the other hand, are only visible within the class and are changeable only within the class.
You can mark attributes as private attributes to protect these against access from outside. The private components of the class are invisible to the outside user.
Here, r_veh which belongs to lcl_rental can only refer to public attributes of the class lcl_vehicle.


ACCESSING PRIVATE ATTRIBUTES



PUBLIC SECTION and PRIVATE SECTION of a class define the corresponding public and private attributes of that class. It is syntactically impossible to access private attributes directly from outside. However, you can do so by using public methods that change the attributes.

COMPARISON OF INSTANCE ATTRIBUTE WITH STATIC ATTRIBUTE




You can define two kinds of attributes:
  Instance attributes exist once per object, which means, once per runtime instance of the class. They are defined with the syntax element DATA.

  Static attributes exist once for each class and appear for all runtime instances in that class. They are defined with the syntax element CLASS-DATA.

INSTANCE ATTRIBUTES AND STATIC ATTRIBUTES IN THE PROGRAM

For example, let us consider n_o_vehicles to be the static attribute of the class. It exists only once. The instances r_vehicle1, r_vehicle2, and r_vehicle3 are instances of the class lcl_vehicle. All these instances or any number of instances can refer to the static attribute n_o_vehicles. Therefore, instances share their common attributes.

SYNTAX FOR METHODS




Methods are internal procedures in classes that define the behavior of the objects. They can change the state of other elements by accessing all attributes in their class.
Methods have a signature that allows them to receive values when they are called, and in turn, send values back to the calling program.
Methods can have any number of IMPORTING, EXPORTING, and CHANGING parameters. All parameters can be passed by value or reference.
You can use the RETURNING parameter to define functional methods. Methods also support EXCEPTIONS; but only if the signature exceptions are defined using EXCEPTIONS. You can use the RAISING addition to propagate class-based exceptions. However, a combination of both cannot be used. The implementation of the method is defined in the class implementation part as shown.

VISIBILTY SECTIONS OF METHODS




Object r_veh can access only the public attribute set_type of the lcl_vehicle class. Methods also have to be assigned to a visibility section. This determines whether the methods are called from outside the class or only from within the class.
Public methods can be accessed from anywhere; whereas Private methods can only be called within the class.

ACCESSING PRIVATE METHODS




Private methods are defined in the PRIVATE SECTION of a class, whereas public attributes are defined in the PUBLIC SECTION.
It is not possible to directly access private methods from outside. However, a private method can be called by a public method.
In this example, INIT_TYPE is a private method that is called by the public method set_type.

COMPARISON OF STATIC METHOD AND INSTANCE METHOD




There are two types of methods, instance methods and static methods.
An instance method can access both static and instance components. Instance methods are defined using the syntax keyword METHODS.
Static methods are defined at class level. Only static components can be accessed by a static method. These methods are defined using the syntax keyword CLASS-METHODS.
In this example, only the static attribute gv_n_o_vehicles is accessible within the static method get_n_o_vehicles. All other attributes of the class are instance attributes that can only be accessed within instance methods.

VISIBILITY SECTIONS AND UML NOTATION




In a UML class diagram, a class is represented as a rectangular box with the class name first, and class attributes and methods below it. The visibility of components of a class are shown in UML using the characters + and -.
‘+’ indicates that the components are of type Public, while ‘-’ indicates that the components are of type Private. Static components are represented with an underscore.


OVERVIEW OF INSTANCE OF CLASSES


During the program runtime, the class is used to create discrete objects or instances in the memory. This process is called instantiation.
CREATE OBJECT statement is used to create objects. They can only be created and addressed using reference variables. CREATE OBJECT r_vehicle statement creates an instance of the class lcl_vehicle at runtime.

DEFINITION OF REFERENCE VARIABLE




The statement DATA go_vehicle1 TYPE REF TO lcl_vehicle is used to define a reference variable, which is defined as a pointer to objects of type lcl_vehicle. The statement go_vehicle2 is also syntactically correct, and therefore, creates another reference variable which refers to the class lcl_vehicle.


CREATING OBJECTS

The statement CREATE OBJECT creates an object in the memory.
Here, the CREATE OBJECT statement is used to create two objects go_vehicle1 and go_vehicle2.

REVERENCE SEMANTICS OF OBJECT REFERENCES


Reference variables can also be allotted to each other. Here, go_vehicle1, go_vehicle2,and go_vehicle3 are reference variables of the class lcl_vehicle.
The statement go_vehicle2 = go_vehicle1 is syntactically correct. It means that after assignment both the object references would point to the same object.

GARBAGE COLLECTOR


Independent references are those references that are not defined within a class. You cannot access an object if there are no independent references that point to it. Hence, all those objects that cannot be accessed syntactically are deleted by the Garbage Collector.
The Garbage Collector is a routine job that is performed whenever the runtime system does not have any other important tasks to execute.
In this example, the reference to object (2)lcl_object is initialized. Later, as there are no references pointing towards this object, Garbage Collector deletes it. As there are no references pointing to object (4)lcl_object, it is deleted as well.



REFERENCE ADMINISTRATION WITH MULTIPLE INSTANTIATION


If there are several objects that refer to the same class in a program, then it is possible to store all objects together. This can be done by defining an internal table that contains one column with the object references for this class. These objects can be put in the internal table with the usual statements for internal tables, such as APPEND, READ, or LOOP.


EXAMPLE OF AGGREGATION


Any number of objects to the class lcl_vehicle can be created as shown in the slide. Each object in the class lcl_wheel has its own identity. Objects can exist irrespective of the existence of any other object in the class lcl_vehicle.
The desired association appears after references are transferred to the objects of the class lcl_vehicle.


CALLING METHOD


A class consists of attributes and methods. In this example, let us call motor_on method of the class lcl_vehicle. An object reference to the class, go_vehicle uses the data statement. The syntax to call the method motor_on consists of reference variable, followed by object component selector, followed by the method name. The name of the method must be followed by open and close parentheses with a space in-between.


CALLING INSTANCE METHOD - SYNTAX


The syntax for calling instance methods is CALL method ref → method_name. The interface parameters: EXPORTING, IMPORTING, CHANGING, RECEIVING, and EXCEPTIONS can be specified in the method call.
A shorter syntax is also supported. In this case, CALL METHOD is omitted, and the parameters are listed in parentheses. There must be no space before the parentheses, but there must be at least one after the parentheses.
In this example, method call also has RECEIVING parameters which specify that the method is a functional method.


FUNCTIONAL METHODS

Functional methods are defined as methods that have exactly one RETURNING parameter. They can only have IMPORTING parameters and exceptions.
A functional method call will have explicit assignment of RECEIVING parameter. Functional methods can be called implicitly within various expressions such as
  MOVE, CASE, LOOP;

  Logical expressions, such as IF, ELSEIF, WHILE, CHECK, WAIT; and

  Arithmetic expressions and bit expressions, such as COMPUTE.



FUNCTIONAL METHODS - EXAMPLE

In this example, the call of a functional method is shown supplying all the necessary parameters. The second example shows the call of a functional static method in the short form.


ACCESSING PUBLIC ATTRIBUTES

The public attributes of a class can be accessed from outside the same way as method calls.
Static attributes are accessed using classname=>static_attribute.
Instance attributes are accessed with ref → instance_attribute.
However, the instance method call is possible only if the attributes are public.


(INSTANCE) CONSTRUCTOR


Constructor is a special method of a class which is automatically called by the runtime system when an object of the class is created. The constructor is automatically called at runtime with the CREATE OBJECT statement. A constructor can only have IMPORTING parameters and exceptions.

CONSTRUCTOR - EXAMPLE



This example shows how a CONSTRUCTOR is called and implemented. The parameter values are passed to the constructor in the method definition.

EXAMPLE OF STATIC CONSTRUCTOR

Static constructor is a special static method in a class. It is defined as class_constructor. It is executed only once per program (and class). It cannot have parameters or exceptions. The static constructor is called automatically at the first access of the class during the program run.


SELF REFERENCE


An object can address itself by using the predefined reference variable ME within its instance methods. In general, you do not need to use the prefix
me → . However, it can be used to improve readability.

No comments:

Post a Comment