Reading Sample: First-Hand Knowledge
Reading Sample: First-Hand Knowledge
Reading Sample
Modularization involves placing specific sequences of ABAP statements in a
module, instead of placing all the statements in a single main program.
In this sample chapter, you will learn to modularize your program using
object-oriented programming, with classes, global classes, function modules
and subroutines.
Contents
Index
The Author
Brian O‘Neill
Getting Started with ABAP
451 Pages, 2016, $49.95/€49.95
ISBN 978-1-4932-1242-2
www.sap-press.com/3869
© 2016 by Rheinwerk Publishing, Inc. This reading sample may be distributed free of charge. In no way must the file be altered, or
individual pages be removed. The use for any commercial purpose other than promoting the book is strictly prohibited.
Making Programs Modular
Separation of Concerns
Separation of concerns is a principal used to separate a program into
different layers, each with its own function. Imagine an ABAP pro-
gram that was created to report on some data from the database. You
could break that program into three different parts, one part to read
the data from the database, another part to process the data, and a
third part to display the results, as shown conceptually in Figure 6.1.
217
Making Programs Modular Separation of Concerns
6 6
In order to avoid writing procedural nightmare programs, use the Why use separation
REPORT ZABAP_PROGRAM separation of concerns principal to keep each unit focused on per- of concerns?
forming only one function, and name each unit based on the function
that it performs. This makes it much easier to understand the pro-
gram, fix it, and enhance it. Remember that you may write the pro-
READ DATA FROM DATABASE
gram once, but someone else may have to fix or change it, possibly
years later! Therefore, after using the plan in Figure 6.1, if users
returned to you and said that they wanted additional data from the
READ DATA
PROCESS DATA PROCESS DATA database, you would know exactly what unit to change, and if they
DISPLAY DATA wanted the ability to refresh the data, you would know that you can
add the ability to call the read data from the database after displaying
the data. If you had just one long program, it would be harder to find
DISPLAY DATA out exactly where you need to make changes, and you definitely
would not be able to reuse any particular unit; the program would all
be one long unit.
Figure 6.1 Using Seperation of Concerns to Break a Program into Single-Function Of course, each person’s interpretation of a unit focused on perform-
Units
ing only one function might be different. That’s where this concept
can become more of an art than a science. If the units are made too
When you break your program into these three different sections, small, it can be confusing because there are so many; if they are made
you then have one place to make changes to any of those functions. too large, it can be confusing because there’s so much code in a single
Procedural programs Back in the ancient days of computing, people would write long pro- unit. Remember that you’re both writing a program and trying to
grams using punch cards that had to be executed from the beginning make it easy for the next person to fix and enhance.
to the end and probably scheduled to run at a certain time. Today, Figure 6.2 expands on the original conceptual drawing in Figure 6.1 Naming different
applications are used by people in real time, which means that you to demonstrate breaking up and naming units for each function that units
need to change your application to meet the user’s sometimes crazy they perform. This example demonstrates a program that gets a list of
expectations. Programs designed to run from the beginning to end possible flights based on a search, calculates the price of the flight
are called procedural programs. options, and displays the results to the user. Each unit completes one
In a typical ABAP journey, it’s normal to see an old program written function, and each unit has a descriptive name. If a person said that
in a procedural format—and then you’ll hear from a user that the pro- there was an issue with the price being calculated, you would know
gram is supposed to process data in some way that isn’t working. exactly what unit of code he or she was talking about.
You’ll have to go through the long process of reading the program and
debugging to figure out where the data is changed, only to find that
the data is read and changed all over the place.
218 219
Making Programs Modular Introduction to Object-Oriented Programming
6 6
What Is an Object?
READ DATA A programming object is designed around the idea of objects in the
PROCESS DATA PROCESS DATA CALCULATE_TOTAL_PRICE
DISPLAY DATA
real world. A good introductory conceptual example is that of a car.
A car has attributes that describe its current state, such as fuel level
and current speed, and attributes that describe the object, such as
DISPLAY DATA DISPLAY_RESULTS manufacturer and model. There are also a few methods that describe
how we interact with the car, such as accelerate, decelerate, and
refuel. Figure 6.3 shows a conceptual drawing of this car object.
Figure 6.2 Seperation of Concerns with Named Code Units
Attributes Methods
Changing units Just because you created certain units of code when the application
of code was created doesn’t mean that you can’t add more. It’s common to
have to add additional functionality in a single unit of code, in which Accelerate
220 221
Making Programs Modular Structuring Classes
6 6
METHOD ACCELERATE. one object that holds all of the logic for your program. Each method
SPEED = SPEED + 5. will represent a single function, as discussed in the section on the sep-
ENDMETHOD.
aration of concerns principle. Looking back at Figure 6.2, each differ-
Listing 6.1 Pseudocode of Accelerate Method
ent unit could be represented as a method in a flight finder class, as
shown in Figure 6.5.
Classes Now, say that the example in Figure 6.3 specifically refers to a Toyota
Tundra, but you want to create additional objects for different types
Methods
of cars. This is where classes come in. Each object is actually an instan-
tiation of a class, and you can have multiple objects of the same class. Attributes GET_AVAILABLE_FLIGHTS
Again think back to the real-life example of a car; the Toyota Tundra
is a type of car, and all cars can accelerate, decelerate, and refuel, but
GET_CUSTOMER_DATA
this particular car is going at a certain speed and has a certain fuel
level. When creating objects, all of the code is stored in the class, but
you can create multiple objects that use that code, and each will have CALCULATE_TOTAL_PRICE
its own set of attributes to describe it, as shown conceptually in Fig-
ure 6.4. You can think of the class in this example as a mold, whereas
DISPLAY_RESULTS
the objects are those items created from that mold.
Structuring Classes
Now that you understand some of the concepts of object-oriented
programming, you can begin to learn how to create classes and
Car Object 1 Car Object 2
Fuel: 100 Fuel: 10 objects in ABAP. If the object-oriented concepts do not make sense
Speed: 10 Speed: 0
Brand: Toyota Brand: Nissan yet, perhaps seeing the actual code in action will help. We’ll first
Manufacturer: Tundra Manufacturer: Sentra
cover how to create a local class within a program and then how to
create a global class that can be used across multiple programs.
Figure 6.4 Relationship between Class and Object
Implementation vs. Definition
Modularizing with Object-Oriented Programming In ABAP, every class requires a definition and an implementation.
Just because you are using object-oriented programming doesn’t The definition lists the different attributes and methods of a class,
mean you have to use it to build multiple objects. You could also have
222 223
Making Programs Modular Structuring Classes
6 6
whereas the implementation contains the actual code for all of the CLASS lcl_car IMPLEMENTATION.
methods. The definition must come before the implementation and ENDCLASS.
must also come before an object is created from the class. The class is Listing 6.3 Creating an Object from a Class
224 225
Making Programs Modular Structuring Classes
6 6
methods. Listing 6.5 adds public attributes for fuel, speed, brand, ENDCLASS.
and manufacturer and a private attribute for the current gear. ClASS lcl_car IMPLEMENTATION.
METHOD accelerate.
Read Only attributes Public attributes can also be given a READ-ONLY property, which will ENDMETHOD.
METHOD decelerate.
make them readable outside of the class and changeable only from ENDMETHOD.
within the class. In Listing 6.5, the attribute d_manufacturer is set to METHOD refuel.
be read-only. ENDMETHOD.
ENDCLASS.
CLASS lcl_car DEFINITION. Listing 6.6 Adding Public Classes to the Car Class
PUBLIC SECTION.
DATA: d_fuel TYPE i,
d_speed TYPE i, Now, you can add code to the methods. The code will go in the class Implementation
d_brand TYPE string, implementation section, and each method will share all of the attri-
d_manufacturer TYPE string READ-ONLY. butes declared in the definition. Listing 6.7 adds some programming
PRIVATE SECTION.
DATA: d_gear TYPE i. logic to each of the methods, and you can see that they are all able to
ENDCLASS. access the class attributes.
ClASS lcl_car IMPLEMENTATION.
ENDCLASS. You can also declare variables within methods, such as ld_max in the Local variables
Listing 6.5 Adding Public and Private Attributes to the Car Class REFUEL method shown in Figure 6.11. These variables are considered
local variables since they will not be visible or usable outside of the
Class Methods methods in which they’re declared. For that reason, they are prefixed
Definition Methods are the place to store all of your code, in single units of work with a ld_ meaning local data variable, instead of d_, meaning global
designed to complete one function. Each method should have a name data variable.
describing the action that it will complete. First, you have to define CLASS lcl_car DEFINITION.
the method using the keyword METHODS in the class definition, and PUBLIC SECTION.
then write the method’s code in the class implementation in between DATA: d_fuel TYPE i,
d_speed TYPE i,
the words METHOD and ENDMETHOD. Listing 6.6 expands on the car d_brand TYPE string,
example to add the definition and an empty implementation for the d_manufacturer TYPE string.
accelerate, decelerate, and refuel methods. When adding methods, METHODS: accelerate,
decelerate,
you will get a syntax error if the method is not defined in both the
refuel.
definition and implementation of the class. PRIVATE SECTION.
DATA: d_gear TYPE i.
CLASS lcl_car DEFINITION. ENDCLASS.
PUBLIC SECTION. ClASS lcl_car IMPLEMENTATION.
DATA: d_fuel TYPE i, METHOD accelerate.
d_speed TYPE i, d_speed = d_speed + 5.
d_brand TYPE string, d_fuel = d_fuel – 5.
d_manufacturer TYPE string. ENDMETHOD.
METHODS: accelerate, METHOD decelerate.
decelerate, d_speed = d_speed – 5.
refuel. d_fuel = d_fuel – 2.
PRIVATE SECTION. ENDMETHOD.
DATA: d_gear TYPE i. METHOD refuel.
226 227
Making Programs Modular Structuring Classes
6 6
The code for calling methods has to be included after the object has
been defined and created, but it can come before the definition of the
Figure 6.6 Execution Stack in Eclipse
object, as shown in Listing 6.8.
CLASS lcl_car DEFINITION. Now, we can select the start-of-selection item in the stack to see
PUBLIC SECTION. the line of code where the accelerate method was called as shown in
DATA: d_fuel TYPE i,
d_speed TYPE i, Figure 6.7.
d_brand TYPE string,
d_manufacturer TYPE string.
METHODS: accelerate,
decelerate,
Figure 6.7 Eclipse Showing Where the Start-Of-Selection Stack
refuel.
PRIVATE SECTION.
DATA: d_gear TYPE i. We can do the same thing from the SAP GUI debugger, when your
ENDCLASS.
breakpoint inside of the accelerate method is hit, you will notice the
DATA: o_car TYPE REF TO lcl_car.
CREATE OBJECT o_car. ABAP and Screen Stack section will appear as shown in Figure 6.8.
o_car->accelerate( ).
ClASS lcl_car IMPLEMENTATION.
METHOD accelerate.
d_speed = d_speed + 5.
d_fuel = d_fuel – 5.
ENDMETHOD.
METHOD decelerate.
d_speed = d_speed – 5.
d_fuel = d_fuel – 2. Figure 6.8 ABAP and Screen Stack in SAP GUI
228 229
Making Programs Modular Structuring Classes
6 6
We can then click the START-OF-SELECTION item and the debugger CLASS lcl_car DEFINITION.
will bring up the section of code that called our accelerate method as PUBLIC SECTION.
DATA: d_fuel TYPE i,
shown in Figure 6.9. d_speed TYPE i,
d_brand TYPE string,
d_manufacturer TYPE string.
METHODS: accelerate IMPORTING ip_accel_rate TYPE i,
decelerate,
refuel.
PRIVATE SECTION.
Figure 6.9 SAP GUI Debugger Execution Stack DATA: d_gear TYPE i.
ENDCLASS.
DATA: o_car TYPE REF TO lcl_car.
Importing, Returning, Exporting, and Changing CREATE OBJECT o_car.
o_car->accelerate( 5 ).
When using your car class, users do not want to accelerate at a rate of ClASS lcl_car IMPLEMENTATION.
5; they want to specify the amount of acceleration to occur, which METHOD accelerate.
makes sense. There are a few ways to pass data to and from methods, d_speed = d_speed + ip_accel_rate.
d_fuel = d_fuel – 5.
as described in Table 6.2.
ENDMETHOD.
METHOD decelerate.
Importing A copy of one or more variables is passed to the method. d_speed = d_speed – 5.
Returning The actual variable is returned by the method. Returning can d_fuel = d_fuel – 2.
only be used to return one variable. ENDMETHOD.
METHOD refuel.
Exporting A copy of one or more variables are returned from the d_fuel = 100.
method. ENDMETHOD.
ENDCLASS.
Changing The actual variable is passed to the method, and any changes
to that variable will change the original. (Also known as Listing 6.9 Adding the Ability to Import Variables in Methods
passing by reference.)
Next, you can change the method to check if the fuel is at zero; if it is, Returning
Table 6.2 Ways to Pass Data to and from a Method
then the car will not accelerate. When you call the method, you want
to know if it worked or not, so return a Boolean parameter that will
Importing You can change the accelerate method to import a variable to indi- be true if the method worked and false if it did not. The Boolean
cate the amount of speed that you want to increase by. This is handled parameter is defined in the class definition using the RETURNING key-
in Listing 6.9 by adding the IMPORTING command followed by a vari- word followed by VALUE and the variable name within parentheses, as
able definition for the variable that will be copied in to the method shown in Listing 6.10, with the prefix rp indicating a returning
and used to set the rate of acceleration for the car object. After adding parameter.
the IMPORTING variable in the definition, that variable can now be
accessed in the method implementation. The prefix ip here indicates Because the returning parameter is a Boolean, also create the Boolean
an IMPORTING parameter. variable d_is_success in the main program and set it to the result of
the method call in Listing 6.10, meaning that d_is_success will be set
Now that you’ve defined the IMPORTING parameter, you also can pass to the value of rp_is_success after calling the accelerate method.
the value for that parameter within the parentheses when calling the
method, as shown in Listing 6.9.
230 231
Making Programs Modular Structuring Classes
6 6
232 233
Making Programs Modular Structuring Classes
6 6
234 235
Making Programs Modular Structuring Classes
6 6
236 237
Making Programs Modular Structuring Classes
6 6
call, call with a value of one less than the current importing parameter
and add the result of that to the result of calling the method with a rp_value = calculate(4-1) + calculate(4-2).
value of two less than the current importing parameter. You don’t
want the recursive call to run forever, of course, so if the method is
called with a value of one or less, it will return the value of the param-
eter that was called. Try running the code in Listing 6.17 in debug rp_value = calculate(3-1) + calculate(3-2). rp_value = calculate(2-1) + calculate(2-2).
mode and step through the program to see the recursion in action.
…
CLASS lcl_truck DEFINITION
INHERITING FROM lcl_car.
ENDCLASS.
238 239
Making Programs Modular Global Classes
6 6
240 241
Making Programs Modular Global Classes
6 6
Multiple views The code for creating and changing the classes is mostly the same as
what you saw for local classes. When using SAP GUI to create the
class, there are two views: a source code view and a forms view. The
resulting code will be the same, but the forms view allows the ABAP
system to write some of the code itself.
Source control One thing that is different about using global classes is the way that
they’re broken up into different pieces. Each piece has its own source
control history and must be activated on its own. The breakup of a
class into different pieces makes it possible for multiple developers to
work on the same class simultaneously.
The different pieces of a global class are the public, private, and pro-
tected sections and each method implementation. This allows you to
Figure 6.11 Creating a New Global Class in Eclipse
treat each method as an individual program in terms of source control
and activation. The public, private, and protected sections are a bit of
You’ll see your new class with the basic structure for a class laid out Global class
a special case, however. These sections are automatically generated keywords
for you, as shown in Figure 6.12. This should look familiar; it’s the
when using the forms view in SAP GUI, so any comments entered in
same structure that you saw with the local classes. The only change is
these areas will be overwritten. You can still create and edit these sec-
the addition of the PUBLIC keyword, indicating a global class. Addi-
tions with your own code, which will be kept, but any comments will
tionally, FINAL keyword is optional and indicates that the class cannot
be lost.
be inherited from and the CREATE PUBLIC keyword, allows an object
to be created from the class anywhere where the class is visible.
How to Create Global Classes in Eclipse
Using Eclipse to create classes is the preferred method and we’ll look
at that first, but we will also cover how to create them using Transac-
tion SE80 later in the section.
To begin, select File 폷 New 폷 ABAP Class; you’ll see the New ABAP
Class wizard appear. Select the package $TMP to save the new class
as a local object, enter “ZCL_GLOBAL_CLASS” as the class name, and
enter “Global Class” as the description, as shown in Figure 6.11. Just
as with ABAP programs, your class needs to be prefixed with a Z. You
can use the prefix ZCL to indicate that the class you’re creating is a
Figure 6.12 New Class Created in Eclipse
custom global class.
242 243
Making Programs Modular Global Classes
6 6
You will be prompted with a popup asking if you want to create ZCL_
GLOBAL_CLASS because it doesn’t exist as shown in Figure 6.13.
Click the Yes button.
In the Create Object Directory Entry popup, click the Local Object Figure 6.16 New Class in the Source Code View
button or enter “$TMP” for the package name, and click the Save but-
ton. For production objects, you should use a package created for Using the Form-Based View in Transaction SE80
your project. You can now return to the form-based view by clicking the Form-
Forms view After creating the class, the editor will show the class in the default Based button, if you are still looking at the source code view. The
forms view. The forms view can be used to change the structure of the form-based view will generate the code for the class definition and
class and add attributes and methods, and it will generate the class add the method definitions to the class implementation. Everything
definition code automatically. You can also click the Source Code- in the form-based view can be done manually in the source code
Based button (Figure 6.15) to view the entire class as code. view; which you use is a matter of personal preference.
244 245
Making Programs Modular Global Classes
6 6
There are many things that you can do with classes that I haven’t cov- The next column, Typing Method, indicates whether the data type
ered yet and things that are out of scope for this book, so don’t feel should be created using the keyword TYPE, TYPE REF TO, or LIKE. Select
overwhelmed by all of the tabs and options in the form-based view. the typing method Type. Next, the Associated Type column indicates
In this section, you will learn how to use the form-based view to add the data type to be used for the parameter; enter “I” to indicate an
methods and attributes to a class. integer data type. You can also add a default value and description; as
with the method description, this description is only visible to other
Creating a method First, create a new method. To do so, select the Methods tab and
developers using the form-based view.
enter “METHOD1” in the first row of the Method column; this will
name your new method METHOD1. Next, under Level, select Instance Next, add a second parameter named “rp_value”. This parameter
Method. When you worked with local classes earlier in the chapter, should be of type returning with a typing method of TYPE and an asso-
those were instance methods; static methods are out of scope for this ciated type of i for integer. Both parameters are shown in Figure 6.18.
book and should be avoided if possible.
Next, select Public under Visibility; this will set the method as public
by defining it in the public section of the class definition. You can also
add a description in the last column, which will only be visible from
the form-based view. The name of your method should typically be
descriptive enough on its own. The end result should look as shown
in Figure 6.17.
Figure 6.18 Adding Parameters Using the Form-Based View
Now, click the Methods button to return to the methods list, and Method
double-click your method to enter the method implementation, implementation
where you can write your code. You will notice that the editor
restricts you to only the method you selected. From here, you can also
Figure 6.17 Adding a Method Using the Form-Based View click the Signature button to toggle the signature display that will
show the parameters you defined for the method as shown in Figure
Parameters Next, select the method and click the Parameter button. From here, 6.19.
you can add parameters for your method. The parameter name goes
in the first column; enter “ip_parameter”. The next column, Type,
indicates whether the parameter is importing, exporting, returning,
or changing. Select Importing for this parameter.
Next, there are two checkboxes, one for Pass Value and one for
Optional. You’re required to pass a value for returning parameters,
but can pass a value for any importing parameters as well. Passing a Figure 6.19 Editng a Method Using the Form-Based View
value for a parameter means that any changes to the parameter in the
method will change the parameter that was passed into the method
Next, click Back to return to the form-based view and click on the Attributes
instead of changing a copy of that parameter. The Optional checkbox
Attributes tab to add some attributes to your new class. Enter “D_I”
will make that parameter optional.
246 247
Making Programs Modular Obsolete Modularization
6 6
in the first row of the Attribute column to indicate that the attribute
name will be D_I. Next, select Instance Attribute under the Level
column. Static attributes are out of scope for this book and should be
avoided if possible.
The button to the right of the Associated Type column is used to cre-
ate complex types (Figure 6.20). Clicking that button will take you to
the public, private, or protected section so that you can add your own
custom attributes that aren’t defined in the ABAP Data Dictionary.
Obsolete Modularization
Now that you’ve added a method and some variables using the form-
based view, save your changes and click the Source Code-Based Now that you are familiar with modularizing your code using the
View button to see the automatically generated code (Figure 6.21). modern object oriented approach, we will also cover some of the
You will notice that the generated code still closely resembles what obsolete modularization techniques. You will need to be familiar with
you saw with the local classes. The only differences are some added these techniques when working with old code or may need to use
comments before the method and an added exclamation point (!) them for technical reasons.
before the method parameters. The exclamation point is an escape
symbol that allows you to use an ABAP keyword such as RETURNING as Function Modules
the name of a variable. Using function modules cannot be avoided in many ABAP programs,
because some of SAP’s standard functionality requires it in areas such
Any additional class examples in this book will only include the actual
as database table locks; however, you should never manually create
code, not the form-based view configuration. You should be familiar
new function modules. Any situation that calls for a function module
enough with classes by this point to use either the form-based view
to be created can use a global class instead. In fact, function modules
or the source code view interchangeably. We recommend using
were actually SAP’s first attempt at making ABAP object oriented.
Eclipse or the source code view exclusively.
With that said, it’s good to understand how function modules work,
because they’re prevalent in many customer systems and standard
248 249
Making Programs Modular Obsolete Modularization
6 6
SAP code and may be required for technical reasons, such as creating In the New ABAP Function Group wizard, enter the package “$TMP” ABAP function group
a remote function call (RFC). to save it as a local object and enter “ZFG_FUNCTION_GROUP” for wizard
the function group name. The function group name will have to start
Function groups Similar to how methods are contained inside of a class, function mod-
with a Z as noted previously for programs and classes to indicate a
ules are contained inside of a function group. The function group is
custom function group. You can also prefix the name with “ZFG” to
created with two include files, one for global data (attributes in
indicate that it is a function group. Remember that the function
classes) and one that contains all of the function modules (methods in
groups are like classes, so the name should indicate the type of object
classes) in the group.
that the function group will be working with. Finally, enter a descrip-
Any global data or function group attributes will hold the same value tion, which may be used by other developers trying to find your func-
until the end of the program, but variables defined in the function tion group. An example of the correct values is shown in Figure 6.23.
module itself will only hold the same value until the end of the func-
tion call.
In your code, you call the function module itself instead of the group,
and there’s only one instance of the function group. This is unlike
class objects, which can have multiple instances, as was illustrated by
the car example in Figure 6.4.
The function group code displayed in Figure 6.24 shows the two INCLUDE
include files that make up the function group. The INCLUDE file ending
in “TOP” will contain any global data variables that will be accessible
by any of the function modules in the function group just like attri-
butes of a class are available for all of the class methods. The INCLUDE
ending in UXX will contain INCLUDEs for all of the function modules
created, which are just like class methods.
To create the function module, select File 폷 New 폷 Other..., expand Function module
the ABAP folder, and select ABAP Function Module. You can also
right-click the function group you just created from the Eclipse proj-
ect explorer and select New 폷 ABAP Function Module. This action
will open the New ABAP Function Module popup (Figure 6.25).
Figure 6.22 Creating a New ABAP Function Group
250 251
Making Programs Modular Obsolete Modularization
6 6
The new function module should open, and you can enter any code
in between the FUNCTION and ENDFUNCTION keywords.
Just like class methods, function modules have IMPORTING, EXPORTING, Function module
and CHANGING parameters. These are defined in the function module parameters
by entering the type of parameter followed by a declaration of the
data type, as shown in Listing 6.21.
FUNCTION ZFM_NEW_FUNCTION_MODULE.
IMPORTING
ip_param TYPE i.
EXPORTING
ep_param TYPE i.
CHANGING
cp_param TYPE i.
252 253
Making Programs Modular Obsolete Modularization
6 6
You will be prompted with a popup asking if you want to create ZFG_ Figure 6.29). The INCLUDE files ending in TOP will contain any global
FUNCTION_GROUP because it doesn’t exist (Figure 6.27). Click the data variables that will be accessible by any of the function modules
Yes Button. in the function group. The INCLUDE ending in UXX will contain
INCLUDEs for all of the function modules created.
Creating a You’ll then be prompted with the Create Function Group popup Figure 6.29 New Function Group Files in SE80
function group pictured in Figure 6.28. Leave the function group name as ZFG_
FUNCTION_GROUP, and enter “New function group” in the Short
To create the function module, you can either select Function Mod- Creating a function
text textbox. The Short text and Function group values are used by module
ule from the dropdown, type “ZFM_NEW_FUNCTIONMODULE” in
other developers trying to find your function group, so they should
the textbox, and press (Enter), or you can right-click the zfg_func-
typically describe the type of data or objects that you’re working
tion_group folder and select Create 폷 Function Group.
with.
You will then see the Create Function Module popup pictured in
The Person Responsible field will default to your username. You can
Figure 6.30. From the popup, enter “Z_NEW_FUNCTION_MODULE”
leave this as is or change it, depending on your company’s standards.
for the function module name; unlike a global class method, it must
Next, click the Save button to continue.
be prefixed with Z. Because the code doesn’t call the function group
but instead calls the function module directly, the function module
name is global, and each name can only be used once. A good practice
is to prefix the function module name with something indicating the
function group name.
Next, ensure that Function group is set to the correct value; it should
be ZFG_FUNCTION_GROUP for this example. Finally, to benefit
other developers trying to find your function module, enter a descrip-
Figure 6.28 Create Function Group Popup tion of what the function module does in the Short text field; for this
example, enter “Creating a new function module”. Then, click Save.
In the Create Object Directory Entry popup, click the Local Object
button or enter “$TMP” for the package name, and click the Save but-
ton. For production function groups, you should use a package cre-
ated for your project.
Include files Your function group has now been created containing two include
files, which you should see listed on the left side of the screen (see Figure 6.30 Create Function Module Popup
254 255
Making Programs Modular Obsolete Modularization
6 6
Function module You will now see a screen similar to the global class form-based view. Now, you can select the Source Code tab, where you will be able to
parameters Just like class methods, function modules have IMPORTING, EXPORTING, make changes to the function module, just as you made changes ear-
and CHANGING parameters. These are defined in the Import, Export, lier to the method of a global class.
and Changing tabs. Function modules also have a Tables tab used to
define parameters that are passed as tables, which is obsolete and Calling Function Modules
should be avoided. Instead of using the tables parameters, you should You can call a function module using the CALL FUNCTION keyword fol-
pass a table type in one of the other parameters. lowed by the function module name in single quotes ('). The param-
eters are passed by indicating the type of parameter and then the
To add the IMPORTING parameter, select the Import tab and enter “IP_
parameter name, equals sign, and the value that you want to pass to
PARAM” for the parameter name, “TYPE” for Typing and “I” for Asso-
the parameter. Like we saw with class methods, a parameter import-
ciated Type as shown in Figure 6.31. This will create an importing
ing into the function module is exporting from your code. The param-
parameter of IP_PARAM.
eters importing into your program are always optional when calling
a function module. An example calling Z_NEW_FUNCTION_MODULE is
shown in Listing 6.22.
Subroutines are easy to create. They use the FORM keyword followed Perform
by the subroutine name to define the beginning of the subroutine
and ENDFORM to define the end of the subroutine. A subroutine can
be called using the PERFORM keyword followed by the subroutine
Figure 6.33 Adding a Changing Parameter to a Function Module name and will execute any code within that subroutine, as shown in
256 257
Making Programs Modular Summary
6 6
Listing 6.23. No additional code can be entered after ENDFORM, just We then covered global classes, which can be called by any program
additional subroutines. in the system, and how to create them both in Eclipse and using
Transaction SE80 in SAP GUI.
PERFORM my_subroutine.
FORM my_subroutine. The chapter concluded by looking at some obsolete code modulariza-
WRITE: ‘Hello World’.
ENDFORM. tion techniques using function modules and subroutines. Even
Listing 6.23 Using a Subroutine though you shouldn’t be writing new subroutines and function mod-
ules, these are important to understand in order to maintain old
Declaring data in As with methods, local data can be declared within the subroutine ABAP systems.
a subroutine and will only be accessible within that subroutine. Subroutines can In the next chapter, you will take everything you’ve learned so far in
also import parameters with the USING keyword and change parame- the book and apply it to create a new custom application that will run
ters with the CHANGING parameter. These parameters work just like inside your ABAP system.
their function module and class-based counterparts. An example of a
subroutine with parameters is shown in Listing 6.24.
ENDFORM.
Listing 6.24 Subroutine with USING and CHANGING Parameters
Summary
This chapter covered some modularization concepts, such as using
separation of concerns to divide code into units that each complete
only one function, and introduced object-oriented programming as a
way to modularize code to meet the separation of concerns principle.
Next, you learned how to create classes and objects in ABAP. You dis-
covered how methods can be used not only to modularize your code
but also to make it compact through options such as recursive method
calls.
258 259
Contents
Introduction ................................................................................. 15
7
Contents Contents
8 9
Contents Contents
Obsolete Database Access Keywords .................................... 180 6 Making Programs Modular ...................................... 217
SELECT…ENDSELECT ..................................................... 181
Separation of Concerns ......................................................... 217
Short Form Open SQL .................................................... 181
Introduction to Object-Oriented Programming ..................... 220
Summary .............................................................................. 181
What Is an Object? ......................................................... 221
Modularizing with Object-Oriented Programming .......... 222
5 Storing Data in Working Memory ........................... 183 Structuring Classes ................................................................ 223
Using ABAP Data Dictionary Data Types ............................... 183 Implementation vs. Definition ........................................ 223
Data Types ..................................................................... 183 Creating Objects ............................................................. 224
Creating Your Own Structures ........................................ 185 Public and Private Sections ............................................. 225
Field Symbols ................................................................. 186 Class Methods ................................................................ 226
Standard Table ...................................................................... 188 Importing, Returning, Exporting, and Changing .............. 230
Defining Standard Tables ................................................ 188 Constructors ................................................................... 236
READ TABLE .................................................................. 190 Recursion ....................................................................... 237
LOOP AT ........................................................................ 193 Inheritance ..................................................................... 239
Inserting Rows in a Standard Table ................................. 195 Global Classes ....................................................................... 241
Changing Rows of a Standard Table ................................ 196 How to Create Global Classes in Eclipse .......................... 242
Deleting Rows of a Standard Table ................................. 197 How to Create Global Classes in Transaction SE80 .......... 243
Sorted Table ......................................................................... 199 Using the Form-Based View in Transaction SE80 ............ 245
Defining Sorted Tables ................................................... 199 Obsolete Modularization ...................................................... 249
Inserting, Changing, and Deleting Sorted Rows .............. 200 Function Modules .......................................................... 249
BINARY SEARCH ............................................................ 202 Form Subroutines ........................................................... 257
DELETE ADJACENT DUPLICATES FROM ........................ 204 Summary .............................................................................. 258
Hashed Table ........................................................................ 205
Defining Hashed Tables .................................................. 205 7 Creating a Shopping Cart Example .......................... 261
Reading Hashed Tables ................................................... 206
The Design ........................................................................... 262
Inserting, Changing, and Deleting Hashed Table Rows .... 207
The Database ................................................................. 263
Which Table Should Be Used? .............................................. 208
The Global Class ............................................................. 263
Updating ABAP Data Dictionary Table Type .......................... 210
The Access Programs ...................................................... 264
Copying Table Data .............................................................. 212
Database Solution ................................................................. 266
Displaying Data from Working Memory ................................ 213
Data Elements ................................................................ 266
Obsolete Working Memory Syntax ....................................... 214
Transparent Tables ......................................................... 271
WITH HEADER LINE ...................................................... 215
Accessing the Database Solution ........................................... 280
OCCURS ......................................................................... 215
Creating Classic Screens for the Solution ............................... 286
Square Brackets ([]) ........................................................ 215
Product Maintenance Program ....................................... 286
Short Form Table Access ................................................. 215
Shopping Cart Maintenance Program ............................. 290
Summary .............................................................................. 216
Summary .............................................................................. 295
10 11
Contents Contents
12 13
Index
445
Index Index
446 447
Index Index
Inline data declaration, 51, 153, Loop, 60 Object-oriented programming (Cont.) Parameter ID, 132
289, 293 infinite, 60 class definition, 223–224 Pooled tables, 108
INNER JOIN, 160, 163, 285 LOOP AT, 193 class implementation, 223–224 Primary key, 101, 111, 282
INSERT, 156, 195, 210 BINARY SEARCH, 202 CONSTRUCTOR, 236 Procedural programming, 218
hashed table, 207 hashed table, 207 CREATE OBJECT, 224 Program attributes
INDEX, 195 WHERE, 194 CREATE PUBLIC, 243 authorization group, 42
LINES FROM, 195 EXPORTING, 230, 234 editor lock, 42
sorted table, 201 M FINAL, 243 fixed point arithmetic, 42
Insert anomaly, 102 global classes, 241–242, 263 logical database, 42
Integrated development Maintenance dialog, 141 IMPORTING, 230, 233 selection screen, 42
environments, 395 MANDT, 106, 124, 126, 157, 189 INHERITING FROM, 239 start using variant, 42
Internal tables, 183, 208 Many-to-many relationship, 105 method, 221, 226, 228 status, 42
hashed table, 205, 209 Message class, 364, 371, 392 method chaining, 232 unicode checks active, 42
key, 189 &, 371 object, 221 Program lifecycle events, 75
SORT, 200 create, 367 OO-ABAP, 220 Promote optimistic lock, 171
sorted table, 199, 208 long text, 369 OPTIONAL, 233 Pseudocode, 283
standard table, 188, 208 MESSAGE, 368 private section, 225
INTO, 170 WITH, 371 protected section, 225, 240 Q
IS NULL, 156 Method, 300 public section, 225
ITAB_ILLEGAL_SORT_ORDER, 200 MOD, 53 READ-ONLY attributes, 226 Quantities, 341
Modalities, 104 recursion, 237 QUAN, 342
J MODIFY, 158, 210, 284, 289 REDEFINITION, 240 UNIT, 342
hashed table, 207 RETURNING, 230–231 UNIT_CONVERSION_SIMPLE, 344
Joins, 179 sorted table, 201 returning parameters, 236
Junction Table, 105 MODIFY TABLE, 196 subclass, 239 R
INDEX, 197 superclass, 239
K WHERE, 196 TYPE REF TO, 224 RAISE, 387
Modularize ABAP, 217 One-to-many relationship, 104 RAISING, 381–382
Key, 111 MOVE, 52 One-to-one relationship, 104 Ranges, 168
Key fields/candidate, 125 MOVE-CORRESPONDING, 212 Open SQL, 149 READ TABLE, 190, 210
MODIFY, 184 ASSIGNING, 190–191
L N Optimistic lock, 171 BINARY SEARCH, 202
Origin of the input help, 112 hashed table, 206
LEFT OUTER JOIN, 163 New Open SQL, 169 INDEX, 191
LENGTH, 50, 68–69 Nonidentifying relationship, 104 P INTO, 190–191
Lifecycle event, 75 NoSQL, 100 WITH KEY, 207
LIKE, 184, 189 NULL, 111 Package, 109 WITH TABLE KEY, 192
LINE OF, 184 Numeric data types, 47 Packed numbers, 48 Relational Database Management
LOAD-OF-PROGRAM, 75 PARAMETER, 65–66, 69 System (RDBMS), 100
Lock O AS CHECKBOX, 70 REPORT, 40, 44, 75, 77
mode, 172 AS LISTBOX VISIBLE LENGTH, 70
objects, 174 Object, 293 LOWER CASE, 287 S
parameter, 173 Object-oriented programming, 220 OBLIGATORY, 70, 291
Log data options, 116 attributes, 225 RADIOBUTTON GROUP, 70, S/4 HANA, 22
Logical storage parameters, 115 CHANGING, 230, 235 287, 291 SAIRPORT, 106
class, 222–224
448 449
Index Index
450 451
First-hand knowledge.
Brian O‘Neill We hope you have enjoyed this reading sample. You may recommend
Getting Started with ABAP or pass it on to others, but only in its entirety, including all pages. This
reading sample and all its parts are protected by copyright law. All usage
451 Pages, 2016, $49.95/€49.95
and exploitation rights are reserved by the author and the publisher.
ISBN 978-1-4932-1242-2
© 2016 by Rheinwerk Publishing, Inc. This reading sample may be distributed free of charge. In no way must the file be alte-
www.sap-press.com/3869
red, or individual pages be removed. The use for any commercial purpose other than promoting the book is strictly prohibited.