Top Banner
NetWeaver Developer’s Guide Release: SAP NetWeaver 2004s Using ABAP
63

Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

Mar 11, 2018

Download

Documents

dokhanh
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

NetWeaver Developer’s Guide Release: SAP NetWeaver 2004s

Using ABAP

Page 2: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

SAP AG Dietmar-Hopp-Allee 16 69190 Walldorf Germany T +49/18 05/34 34 24 F +49/18 05/34 34 20 www.sap.com

© Copyright 2005 SAP AG. All rights reserved. No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. The information contained herein may be changed without prior notice. Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. Microsoft, Windows, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation. IBM, DB2, DB2 Universal Database, OS/2, Parallel Sysplex, MVS/ESA, AIX, S/390, AS/400, OS/390, OS/400, iSeries, pSeries, xSeries, zSeries, z/OS, AFP, Intelligent Miner, WebSphere, Netfinity, Tivoli, and Informix are trademarks or registered trademarks of IBM Corporation in the United States and/or other countries. Oracle is a registered trademark of Oracle Corporation. UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group. Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWin are trademarks or registered trademarks of Citrix Systems, Inc. HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts Institute of Technology. Java is a registered trademark of Sun Microsystems, Inc. JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape. MaxDB is a trademark of MySQL AB, Sweden.

SAP, R/3, mySAP, mySAP.com, xApps, xApp, SAP NetWeaver, and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the world. All other product and service names mentioned are the trademarks of their respective companies. Data contained in this document serves informational purposes only. National product specifications may vary. These materials are subject to change without notice. These materials are provided by SAP AG and its affiliated companies ("SAP Group") for informational purposes only, without representation or warranty of any kind, and SAP Group shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP Group products and services are those that are set forth in the express warranty statements accompanying such products and services, if any. Nothing herein should be construed as constituting an additional warranty. Disclaimer Some components of this product are based on Java™. Any code change in these components may cause unpredictable and severe malfunctions and is therefore expressively prohibited, as is any decompilation of these components. Any Java™ Source Code delivered with this product is only to be used by SAP’s Support Services and may not be modified or altered in any way. Any software coding and/or code lines / strings ("Code") included in this documentation are only examples and are not intended to be used in a productive system environment. The Code is only intended better explain and visualize the syntax and phrasing rules of certain coding. SAP does not warrant the correctness and completeness of the Code given herein, and SAP shall not be liable for errors or damages caused by the usage of the Code, except if such damages were caused by SAP intentionally or grossly negligent.

Page 3: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

T yp o g r a p h i c C o n v e n t i o n s

Type Style Represents

Example Text Words or characters quoted from the screen. These include field names, screen titles, pushbuttons labels, menu names, menu paths, and menu options.

Cross-references to other documentation.

Example text Emphasized words or phrases in body text, graphic titles, and table titles.

EXAMPLE TEXT Technical names of system objects. These include report names, program names, transaction codes, table names, and key concepts of a programming language when they are surrounded by body text, for example, SELECT and INCLUDE.

Example text Output on the screen. This includes file and directory names and their paths, messages, names of variables and parameters, source text, and names of installation, upgrade and database tools.

Example text Exact user entry. These are words or characters that you enter in the system exactly as they appear in the documentation.

<Example text> Variable user entry. Angle brackets indicate that you replace these words and characters with appropriate entries to make entries in the system.

EXAMPLE TEXT Keys on the keyboard, for example, F2 or ENTER.

I c o n s

Icon Meaning

Caution

Example

Note

Recommendation

Syntax

Page 4: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

Contents

1 USING ABAP..................................................................................................................... 1 2 GETTING INVOLVED........................................................................................................ 2

2.1 The Origins of ABAP – an Overview......................................................................... 2 2.2 ABAP and Its Infrastructure....................................................................................... 3 2.3 ABAP and the SAP NW Application Server .............................................................. 4

3 GO AND CREATE ............................................................................................................. 5 3.1 Creating a Database Table and Data Elements ....................................................... 6 3.2 Creating a Database Table – Part 1 ......................................................................... 6 3.3 Creating Data Elements ............................................................................................ 7 3.4 Creating a Database Table – Part 2 ......................................................................... 8 3.5 Defining the Basic Attributes of a Global Class ...................................................... 10 3.6 Methods, Types, and Attributes of a Global Class.................................................. 11

4 CORE DEVELOPMENT TASKS ..................................................................................... 16 4.1 UI Technology ......................................................................................................... 17 4.2 Advantages of ABAP Objects ................................................................................. 18

4.2.1 Why You Should Use ABAP Objects ........................................................... 18 4.2.2 Using ABAP Objects - Best Practices .......................................................... 20

4.3 Sharing Data ........................................................................................................... 20 4.3.1 Shared Objects - Basic Features ................................................................. 21 4.3.2 Shared Objects - Advanced Features .......................................................... 22 4.3.3 Best Practices............................................................................................... 23

4.4 Exception Handling ................................................................................................. 24 4.4.1 Class-Based Exceptions in ABAP................................................................ 24 4.4.2 Basic Features.............................................................................................. 24 4.4.3 Planning Exception Handling and Delegating Exceptions ........................... 25 4.4.4 The Three Exception Classes in ABAP........................................................ 27 4.4.5 Defining an Exception Class ........................................................................ 29 4.4.6 New Exceptions and Former Concepts of Error Handling ........................... 30

4.5 Developing Persistence .......................................................................................... 30 4.5.1 The Standard Path to Persistence ............................................................... 31 4.5.2 Other Persistence Options ........................................................................... 33 4.5.3 All or Nothing – Database and SAP Transactions ....................................... 34 4.5.4 Exclusive Database Access - Lock Concept of the SAP NW AS................. 35 4.5.5 Restricting Access - Authorization Concept of the SAP NW AS.................. 36

4.6 Using Connectivity and Interoperability................................................................... 37 4.6.1 The Integration Strategy of SAP and Web Services .................................... 38 4.6.2 How Web Services Function ........................................................................ 38 4.6.3 Generating Interfaces and Proxies – The Outside-In Approach .................. 40 4.6.4 XML-Based Process Integration with the Exchange Infrastructure.............. 41

4.7 Making Enhancements............................................................................................ 42 4.7.1 How Do Modification-Free Enhancements Work? ....................................... 42

Page 5: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

4.7.2 Enhancement Framework Details Based on an Example............................ 44 4.7.3 New BAdIs.................................................................................................... 47 4.7.4 The Switch Framework................................................................................. 49

5 ENSURING QUALITY...................................................................................................... 53 5.1 ABAP Unit Tests ..................................................................................................... 53 5.2 Effective Testing with ABAP Unit ............................................................................ 56 5.3 The Philosophy of Unit Tests .................................................................................. 57 5.4 Unit Tests and Transports....................................................................................... 59 5.5 Advantages of ABAP Unit Tests ............................................................................. 59

Page 6: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 1

1 Using ABAP

Being able to use ABAP effectively requires more than just knowledge of the keywords. As a programmer, you need to have a basic understanding of the architecture of the SAP NetWeaver Application Server ABAP and how specific fundamental concepts are implemented in ABAP and its infrastructure.

The aim of this guide is to enable you to use the possibilities of ABAP and the NW Application Server ABAP as effectively as possible. It is to provide you with guidelines on how best to solve certain standard tasks, which are part of any business programming.

Determining the best method to solve a problem in ABAP also means finding the most useful of the various possibilities this language provides. In ABAP, there are often a number of different ways of achieving the same goal. This is the price that has to be paid for evolutionary development and downward compatibility. If old constructs are still required in a new release, because they appear in important application programs, they remain part of the language. Programmers can continue to use them, but should be aware in which cases there are now more effective ways of solving a specific task.

Not only does the ABAP Developer Guider provide programmers with an overview of working with ABAP, but also show the best solution to standard problems of business programming. In any cases where there are multiple, equally useful solutions, this guide is to provide information on their advantages and disadvantages.

The section Getting Involved [Seite 2] introduces the basic features of the ABAP language and the SAP NetWeaver Application Server ABAP. You will learn how ABAP and its tools support the entire lifecycle of an application and what tailor-made, business programming features the language offers. You will also be familiarized with the three-layer architecture of the server and learn why you do not develop locally with ABAP but always centrally on the server.

Programming is a practical experience, and the best way to get an impression of the possibilities of a language and its infrastructure is to write a small program in this language and thus understand its development. The tutorial in the section Go and Create [Seite 5] shows how easily you can use ABAP to create a database table – declaratively and with metadata control – with the relevant fields and attributes. A simple ABAP Objects program manages the data of this table.

With the knowledge gained from these two sections, you are ready to understand how specific basic programming concepts are implemented in ABAP. The section Core Development Tasks [Seite 16] provides an overview of the following topics:

• UI Technology: [Seite 17] The standard Web user interface is Web Dynpro. For special requirements, Business Server Pages can be configured.

• ABAP Objects [Seite 18] offers a number of advantages, even if you want to continue using procedural programming. If you want to use new ABAP features, you have to use object-oriented interfaces anyway.

• Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once at a central location and the different users and programs can then access this data without the need for copying.

• Exception Handling: [Seite 24] With the class-based exception concept of ABAP, you can define a special control flow for a specific error situation and provide the user with information about the error.

• Developing Persistency: [Seite 30] For permanent storage of data in ABAP, you use relational database tables by means of database-independent Open SQL, which is

Page 7: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 2

integrated in ABAP. However, you can also store selected objects transparently or access the integrated database or other databases using proprietary SQL.

• Using Connectivity and Interoperability: [Seite 37] The Exchange Infrastructure and Web services are the means by which developers can implement a service-oriented architecture. With Web services, you can provide and consume services independently of implementation or protocol. Furthermore, you can do so within NetWeaver and in the communication with other systems. With the features of the Exchange Infrastructure, you can enable, manage, and adapt integration scenarios between systems.

• Making Enhancements: [Seite 42] With the Enhancement Framework, you can enhance programs, function modules, and global classes without modification as well as replace existing code. The Switch Framework enables you activate only specific development objects or enhancements in a system.

Testing is an essential part of the software development cycle. The ABAP development environment also provides support for this. The section Ensuring Quality [Seite 53] introduces the basic features of ABAP Unit, a framework with which you can take advantage of unit testing in ABAP. The relevant tools are fully integrated in the standard development environment (SE80, SE24, SE37, SE38) and the code required for testing is implemented in ABAP Objects.

2 Getting Involved When you program with ABAP on the application server, you profit from a range of services, which in other languages would have to be programmed manually with a great amount of effort. Many of these services have resulted from the fact that the SAP NW Application Server is the outcome of a long development period. You are thus benefiting from the experience of many programmers, whose suggestions for improvement are implemented in the server today.

The following provides you with an overview of the origins of ABAP, its infrastructure, and the underlying server architecture. You are thus provided with information introducing you to ABAP and its infrastructure.

If you are used to languages like C or Java, some aspects of programming with ABAP will at first appear unfamiliar, some will seem unusual, and some may even appear impractical. If you use the possibilities of the language effectively, you will soon see that many aspects of business programming can be done with ABAP very simply. In this language, much has already been anticipated and created.

2.1 The Origins of ABAP – an Overview As a programming language of SAP, ABAP (Advanced Business Application Programming) has contributed in no small way to the success of SAP’s application software. Since the seventies, when the language was a macro assembler, ABAP has been consistently optimized for business programming. With the introduction of the R/3 System in the nineties, the ABAP language – now in its fourth generation – became the basis of the entire system, in which all applications and large parts of Basis (as it was referred to at the time) were implemented.

A further, significant step forward was the development of ABAP Objects with Release 4.6. In keeping with SAP’s philosophy of safeguarding the existing billions’ worth of investments

Page 8: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 3

made by customers in ABAP, ABAP Objects is an object-based enhancement of the procedural ABAP language available up to that point. Thanks to this evolutionary strategy with its high level of downward compatibility, the many millions of lines of productive, procedural ABAP coding still run on the NetWeaver Application Server – the name for the technological basis of SAP since Release 6.10.

ABAP is thus not only a mature language that has proven itself in the practical field, but – on the basis of its evolutionary strategy – it continues to be suited to the requirements of business programming. The requests, suggestions, and requirements of the software developers involved have flowed into this language over the years. With the quality of its application programs, it has made SAP a world leader in the development of business software.

Up to the year 2000, ABAP was the sole language in which SAP programmed its successful business software. Since then, the SAP NetWeaver AS combines an ABAP and a J2EE server. SAP uses the opportunities provided by both technologies for its products, but still continues to invest in the further development of ABAP.

2.2 ABAP and Its Infrastructure There are more advantages to programming with ABAP than simply using a sophisticated programming language, and there are very good reasons for this. You require more than just the programming language to write business applications successfully. Efficient programming not only involves the writing of source code, especially in the case of very large projects. A single program with its code is only a building block in a component, which in turn is part of a solution. Furthermore, it is not just the creation of the solution that is relevant, but its entire lifecycle, especially considering that, on average, maintenance costs make up some 60% of software costs.

When you write an ABAP program, it is, from the outset, integrated in an environment that supports its entire lifecycle. The ABAP Development Workbench, the programming environment of the SAP NW AS ABAP, supports the entire software development cycle with tools for:

• Programming in the ABAP language

• Efficient debugging

• Static and dynamic tests of different scales

• Performance analyses

• Organizing large projects

• Updates and importing patches

• Source code management

• Connectors to Java and .NET world

With regard to the actual programming, ABAP has the following features:

• Tailor-made data types for business programming – for example, the internal table, in which you can dynamically create tables with row types structured to any depth and can search their rows for specific fields.

• Object-oriented exception handling

• Support for dynamic programming; from dynamic data generation to dynamic creation of types and entire programs

• Simple management of multilingual texts

Page 9: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 4

• Integration of the DML part of SQL into the language

• Creation of database tables via the definition of metadata

• Definition of various types of data structures, which are then available throughout the server

• Conversion of XML data into ABAP structures

• Simple handling of transactions – that is, program units – which can only be executed fully or not all, in order to ensure data integrity

• Possibility to prepare program enhancements so that customers can enhance programs without modification – that is, without the changes being lost after an update or having to be merged manually

• Possibility to publish procedures as Web services or access Web services as a user

2.3 ABAP and the SAP NW Application Server

Overview If you have experience in programming or languages such as Java and C, you have probably asked yourself why, in the context of ABAP, we speak of the programming environment of the server. In ABAP, you program on the server from the outset. You do not develop the programs locally on your PC, nor do you store the sources in a versioning system or deploy the programs on the server at a later stage.

To program with ABAP, you therefore require access to and developer authorization for the SAP NW Application Server ABAP. You write your programs using the ABAP Editor of the ABAP Workbench, which is also part of the server. Once you activate your source code, platform-independent byte code is generated, which the runtime environment interprets for the program execution.

However, the SAP NW Application Server ABAP not only contains the programming environment with its tools and those for supporting the software lifecycle. ABAP programs always run on the SAP NW AS ABAP and the architecture of the environment in which they run must be taken into account when designing these programs. For this purpose, you first require some information about this architecture.

The Layers of the SAP NW Application Server The SAP NW Application Server ABAP consists of three layers: presentation, application, and database. The database layer of a system is made up of a central database with a database management system and the database itself. It not only contains the user data, but also the entire program code of the SAP NW AS and application programs, all administrative data, and Customizing settings.

The application layer lies between the database layer and the presentation layer. It consists of one or more application servers (more than 100 servers possible) and a single message server, which is responsible for communication and load distribution within this layer. The programs that process the business logic of an application run in this layer. Technically, the actual processing takes place in work processes, which represent operating system processes. A fixed database connection is assigned to each work process. There is no fixed

Page 10: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 5

assignment of users to work processes. A lengthy user session can utilize different work processes sequentially.

The kernel and the Basis services make up the part of the application layer that is specific to both the operating system and the database. They are responsible for user and process management, database access, communication with other systems, as well as system monitoring and administration. The software processes or virtual machines, that interpret the platform-independent byte code as operating system-specific machine language commands, run in the kernel.

The presentation layer represents the interface with the user and is responsible for the screen display. This layer receives user entries – that is, mouse-clicks and keyboard input – and passes them on to the application layer. Furthermore, it receives data from the application layer and displays it to the user.

The purpose of this layering is high performance and scalability. The layer division is purely logical. It does not imply over how many machines the system is distributed. All three layers can actually run on a single computer. However, in the case of large, production applications of customers, this is more of a theoretical possibility, since it would counteract the scalability of the three-level architecture. For demonstration purposes, such as in the case of the mini Basis, it is possible to install all three layers on a single PC. In a production operation, the database usually has a separate machine, as it contains all program, Customizing, and user data. The application layer is spread across several machines, depending on the anticipated load, while the presentation layer runs on the workstations of the individual users.

What Does All this Mean for the Programmer? The layers communicate with one another via network connections, meaning that programmers need not concern themselves with these connections. When you write application programs, these run in the application layer in work processes. Therefore, there is always an open database connection. The specifications of the individual database are of just as little concern to you as the operating system. The kernel is responsible for the communication with all supported operating systems and databases. Therefore, you can program platform-independently.

3 Go and Create In the following sections, you will learn how you can easily use the ABAP Dictionary to create a table in the database and a system-wide class that manages this data.

You create the database table with its fields and the desired attributes via metadata in the ABAP Dictionary. When you activate the object, the table is created on the database. The field types created in the ABAP Dictionary are then available system-wide. You can access them from your ABAP program if you use ABAP Objects to program corresponding service methods for accessing the table.

3.1 Creating a Database Table and Data Elements Before discussing the theory, let us first look at an example that displays how simple it is to program in ABAP. The aim of the development is to have a small program that stores names on the database, finds them again, and lists them on the screen. The first thing you require is a database table in which the names can be stored.

Page 11: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 6

3.2 Creating a Database Table – Part 1 You create a database table in ABAP by creating the metadata for it in the ABAP Dictionary (SE11).

...

1. In the start window of the ABAP Dictionary, Choose the option Database table, enter MYTABLE as the name of the table you want to create, and choose Create.

Enter a short description. In the remainder of the tutorial, you need to enter a descriptive text if the corresponding field is highlighted in pale yellow. This is no longer specially mentioned.

2. On the next screen, enter an A for Application Table in the field Delivery Class. Under

Databrowser/Table View Maint, choose the entry Display/Maintenance Not Allowed. Otherwise the table could be enhanced at a later time ad you would have to observe the rules for enhancing structures according to Unicode checks.

3. Under the Fields tab, enter the table fields.

Page 12: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 7

Name the key field of the table ID by marking the Key column. Name the two other fields FIRSTNAME and SECONDNAME. You must assign a data element to each field. In ABAP, a data element is an unstructured data type that also contains semantic information describing the content of the field. You can create such a document through forward navigation.

4. Enter MYID as data element for the ID field in the first row.

3.3 Creating Data Elements ...

1. When you perform a double-click, you are asked whether you wish to store the data you have entered. Confirm this. You will come across this dialog often during the remainder of the tutorial, but this description will not make special mention of this. Confirm in all these cases.

2. In the next dialog box, confirm that you want to create a data element.

3. In the Short Text field, choose a descriptive text.

4. Select Predefined Type and enter INT4. The length will be generated by the system later when you activate the data element.

You can access a data element in any program system-wide. The database data type is automatically mapped to the corresponding ABAP types.

Page 13: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 8

Switch to the Field Label tab and enter the values listed on the screen below.

If your data element is represented as a table column on the UI, for example, the column heading is taken from these field labels.

5. Save your data by clicking the icon Save and, in the first dialog box that appears, choose Local Object. This means that this table cannot be transported into another system.

6. Now activate the data element by clicking the icon Activate. After you have activated it, the data element is available system-wide.

7. In the same way, create the data types MYFIRSTNAME and MYSECONDNAME using forward navigation. Choose CHARChar with length 25 as the data type for the first name and CHAR with length 50 for the last name. Choose a label of your choice. If you overwrite the lengths allowed, the system will let you know this.

8. Using the blue arrow, navigate back to table MYTALE and complete the table as described in the next section.

3.4 Creating a Database Table – Part 2 ...

1. Press the Technical Settings button.

Page 14: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 9

2. Type in APPLO as data class and 1 as size category.

3. Under Buffering, choose the selection Buffering not allowed. Another choice could define that individual rows or the entire table would be buffered upon access.

4. Save the table. When you do this, you will be requested to enter an enhancement type.

5. Choose the option Cannot be enhanced. In this way you decide whether and how the table can be enhanced later on with additional fields. In this particular case, you have decided that the table cannot be enhanced.

6. Choose Local Object and activate.

As soon as you have activated the table, it is created according to the metadata on the database. You have now created your first table with the ABAP Workbench. In the next step, you will write a class that create the names in this table, searches for and deletes them, and also represents the content of the table.

3.5 Defining the Basic Attributes of a Global Class Create a global class – that is, a class that is available system-wide. The tool used to do this in the SAP NW Application Server is the Class Builder. You can either call it directly using SE24 or via transaction SE80, the Object Navigator, with which you can create and manage different objects. You must first define the basic attributes of the class. ...

Page 15: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 10

1. Enter transaction code SE80 to call the Object Navigator.

2. Choose Class/Interface from the pull-down menu and enter MY_EXAMPLE_CLASS as the name of the class. Then choose Display.

3. Since the class MY_EXAMPLE_CLASS does not yet exist, the system asks you

whether you want to create it.

Confirm that you want to create the object.

4. In the next step, specify that you want to create a class but no interface.

5. Enter a short description for the class and leave the default value Public for

Instantiation and other default settings unchanged. This means, the constructor of the class can be called outside the class and its subclasses. You will create a normal ABAP class, no exception class, or a persistent class, for which the system supports the automatic persisting of the attribute values during commit. Check Final.

Page 16: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 11

6. Save the class.

7. Now assign the class to a package. A package is a unit, whose elements can be collectively transported to another system. For the purposes of this example, no transport is necessary, so no specific development class is required. Choose Local Object. Local objects cannot be transported to another system.

8. Choose Save again.

3.6 Methods, Types, and Attributes of a Global Class

Description of Methods You have now defined the basic attributes of the class MY_EXMAMPLE_CLASS through the menu. Below you define the methods, attributes, and types of the class. The class should have the following methods:

Method Description

SAVE_NAME Takes a name consisting of a first and last name as input parameters, and enters it into the database table MYTABLE.

GET_MAX_INDEX Returns the highest value of the ID column of the table MYTABLE. This is an additional function of SAVE_NAME and helps to ensure that the new table entry gets an ID that does not yet exist.

WRITE_NAMES Outputs all the names for the table MYTABLE.

SEARCH_NAME Checks whether a name already exists in the table MYTABLE. Depending on this, it returns 0 or 1.

CLEAR_TABLE Clears the table MYTABLE.

If you double-click the class name in the tree in the left lower window of SE80, a view of the Class Builder opens in the window on the right. You will see how you can define a method

Page 17: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 12

there, step by step, through the menu. You can do the same for the other methods on your own.

Now create the method SAVE_NAME with an input parameter.

Defining and Implementing the SAVE_NAME Method ...

1. First switch to change mode by choosing the Display/Change icon. The background color of the lines in which you can now enter something changes to white.

2. In the Methods tab under the Methods header, enter the method name.

Click on the field with the column heading Level.

A circle opens up at the end of the field. This leads you to an input help.

This symbol is the symbol used throughout the system for input help. If you click it, you will see a dialog box in which you can choose the allowed options from the displayed list.

3. Choose Instance Method. It would also suffice if you did not open the dialog box, but typed the number assigned to the desired selection – in our case zero – into the appropriate field. If you know the number, you will save yourself time. It is quicker to write “zero” than Instance Method.

Page 18: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 13

4. Choose Public under Visibility and enter a short description of the method.

5. Before you can enter an input parameter for this method, you require a data type for it. Under the Types tab, enter the name MY_NAME, visibility Public, and click on the yellow arrow. Now you get to the Public section, where you can enter the coding for the required data type. You need a structure with the first component FIRSTNAME and the second SECONDNAME. For the respective type of component, you can use the structure that you defined at the beginning in the ABAP Dictionary.

6. In the Public section, you will find the coding type MY_NAME. Since you require a structured type, change the coding as follows:

TYPES: begin of my_name,

firstname type myfirstname, secondname type mysecondname,

end of my_name.

7. Now return to the Methods tab, push the Parameters button, and enter the parameter P_NAME. Choose Importing as type and select the field Pass Value.

Page 19: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 14

8. Under Associated Type, choose a data type for the parameter. Enter the type MY_NAME.

9. Using the button with the blue arrow, return to the method overview, double-click the method name, and enter the implementation of the method:

METHOD save_name.

DATA struc_my_table TYPE mytable. struc_my_table-id = get_max_index( ) + 1.

struc_my_table-firstname = p_name-firstname.

struc_my_table-secondname = p_name-secondname.

INSERT INTO mytable VALUES struc_my_table.

ENDMETHOD.

In the second line, you can see perfectly how easy it is to get a work area in an ABAP program for the work with a database table Assign to a data field the type of the database table as data type. You get a structure wit the line type of the database table. In the next line, the function GET_MAX_INDEX( ) supplies you with the highest index value of the database table. This ensure that the new entry gets a unique index value. In the two next lines, you fill in the respective components of the work area structure with the appropriate components of the input parameter, and then you enter the line into the database table.

Creating and Implementing the Remaining Methods Just like you have seen with the SAVE_NAME method, now create the remaining methods as public instance methods. If possible, choose the data pass Value for the parameters. ...

1. The method GET_MAX_INDEX with the return parameter MAXIMAL of type i:

METHOD get_max_index.

DATA id TYPE i.

SELECT MAX( id ) FROM mytable INTO id.

maximal = id.

ENDMETHOD.

2. The method WRITENAMES without parameters:

METHOD write_names.

DATA: itab TYPE STANDARD TABLE OF mytable,

itab_line LIKE LINE OF itab.

SELECT * FROM mytable INTO TABLE itab.

Page 20: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 15

LOOP AT itab INTO itab_line.

WRITE: AT 5 itab_line-id, AT 15 itab_line-firstname, AT 35 itab_line-secondname.

SKIP.

ENDLOOP.

ENDMETHOD.

You select the data in an internal table and output these, line for line, using the WRITE command.

Note: The WRITE command should be used as little in modern, productive programs in ABAP as the console output function in Java. You can use it for test purposes at any time, as in our program. There are more modern technologies available in ABAP for state-of-the-art user output.

3. The method SEARCH_NAME with the import parameter P_NAME_SEARCHED of the type MY_NAME and the return parameter P_RESULT of the type RETURNVALUE. You create this type in the Class Builder as a public type using TYPES: RETURNVALUE(1) TYPE in the same way as described above for the type MY_NAME:

METHOD search_name.

DATA l_id TYPE myid.

SELECT SINGLE id FROM mytable

INTO l_id

WHERE firstname = p_name_searched-firstname AND

secondname = p_name_searched-secondname.

IF sy-subrc = 0.

* write 'successful'.

p_result = 0.

ELSE.

* write 'not sucessful'.

p_result = 1.

ENDIF.

ENDMETHOD.

Select the ID of the data record in question from the database. If the name exists, the system field SY-SUBRC is set to zero by the system; otherwise, it is set to another value. You can also choose a test output.

4. The method CLEAR_TABLE without parameters:

Page 21: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 16

METHOD clear_mytable.

DELETE FROM mytable.

ENDMETHOD.

4 Core Development Tasks Just as engines, steering, and breaks are required in the manufacture of vehicles, some basic problems must always be solved in the development of business applications – for example, storing data, providing users with a user interface, and enabling communication between systems. Mastering a programming language means knowing the programming concepts of this language that address these problems.

The section Core Development Tasks shows how these fundamental concepts are implemented in ABAP and the SAP NetWeaver Application Server ABAP and thus provides you with a first point of orientation:

• UI Technology: [Seite 17] The standard Web user interface is Web Dynpro. If you require a Web interface that allows a high degree of adjustment to suit specific requirements,Business Server Pages (BSP) are the best UI choice.

• ABAP Objects: [Seite 18] If you develop a new component in ABAP, you should do so using ABAP Objects. Several million lines of productive ABAP code are written in the classic procedural ABAP, but ABAP Objects still offers advantages even if you decide against an object-oriented design: Data can be better encapsulated, the syntax check is stricter and prohibits the old error-prone constructs, and you have more control over the control flow. Furthermore, new ABAP technologies only provide object-oriented interfaces.

• Sharing Data: [Seite 20] Different programs or users often require access to a large amount of aggregated data on the application server. Copying this data and holding it in every program context requires a lot of time and memory space. With ABAP shared objects, you can aggregate data once at a central location and the different users and programs canthen access this data without the need for copying.

• Exception Handling [Seite 24] allows you to specify how the system is to react to a program error of such severity that continuing the normal program flow is not an option. With the class-based exception concept of ABAP, you can define a special control flow for a specific error situation and provide the user with information about the error.

• Persistence: [Seite 30] In ABAP, you have different options for storing your data in the database. With database-independent Open SQL, which is integrated in ABAP, you store the data in relational database tables of the integrated system database. The Object Services store selected objects transparently, and you can use the command EXEC SQL to access the proprietary SQL of the integrated or additional databases.

• Using Connectivity and Interoperability [Seite 37]: Web services are the strategy for communication within NetWeaver and with other systems. With the corresponding tools, you can easily make functions available as services or consume the services of other providers. Furthermore, the Exchange Infrastructure has a number of features to

Page 22: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 17

enable, manage, and adapt the integration scenarios between systems, as well as retain an overview of the relevant metadata. The Exchange Infrastructure and Web services are the means by which developers can implement a service-oriented architecture.

• Making Enhancements: [Seite 42] Special industry solutions, subsidiaries, and customers often have to change or enhance the SAP standard code. With the Enhancement Framework, you can enhance programs, function modules, and global classes without modification as well as replace existing code. Modifications and user exists are thus replaced with a uniform framework. In addition, the Switch Framework enables you activate only specific development objects or enhancements in a system. The code of different additional components can thus be held in one system, even if these components each make different changes to the same code sections of the basis system. With the Switch Framework, you can activate only the desired component and thus only its changes. The other development objects then remain inactive.

4.1 UI Technology Different technologies are available as part of the SAP Web Application Servers for displaying an application to users. Which option is used depends on the application that you want to run. When planning your project, you can decide which UI technology you want to use based on the technical prerequisites as well as the requirements for the planned application.

The SAP GUI for Windows and for Java SAP applications from older releases are usually programmed using dynpro technology. To display applications that were programmed using dynpro technology, a separate software packet is installed on the user’s PC, the SAP GUI for Windows or for Java.

The SAP GUI for Java is also a user interface for displaying dynpro-based applications and is also installed locally on the user’s PC. Unlike the SAP GUI for Windows, the SAP GUI for Java does not depend in the local PC’s operating system. You can find information about the SAP GUI for Java in Note 146505.

The SAP GUI for HTML / Internet Transaction Server The increasing development of the World Wide Web meant that it became necessary to enable existing applications based on dynpro technology to be called using standard browsers via HTTP. The Internet Transaction Server [Extern] (ITS) and the SAP GUI for HTML [Extern] were conceived for this purpose. However, in addition to the flow logic technology [Extern] and the SAP GUI for HTML, there are also additional implementation models for the ITS [Extern].

The ITS consists of a separate software packet that is downstream of the actual backend, which enables the backend server to communicate with the Internet. With Release 6.40 of the SAP Web AS, the SAP GUI for HTML technology and the IAC technology were integrated in the Web Application Server, so that a separate ITS is no longer required for this.

Web-oriented Programming Model Release 6.10 of the SAP Web Application Servers offered programming of Business Server Pages (BSP) for the first time. This programming model is fundamentally different to dynpro programming, and enables an application to be displayed via an HTTP connection using a standard browser. The application-specific display software does not, therefore, need to be installed on the user’s PC.

Page 23: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 18

With Web Dynpro for ABAP [Extern], the SAP Web Application Server provides a new programming model based on the Model View Controller principle as of Release 7.0. The architecture [Extern] of this model is identical to that of the Web AS ABAP and the Web AS Java. Applications that were created using Web Dynpro for ABAP are also displayed using a standard browser on the user’s PC.

4.2 Advantages of ABAP Objects With ABAP, you do not have to worry about the various advantages and disadvantages of object-oriented and procedural programming. ABAP allows you to use both. With regard to the syntactical possibilities of the ABAP language, you can choose between procedural and object-oriented programming. However, there a number of important reasons for using object-oriented programming – that is, ABAP Objects – wherever possible. Even if you do not want use object-oriented programming, using ABAP Objects is still a good idea since it provides some features that procedural programming does not. There are only two purposes for which procedural ABAP is essential:

• Encapsulation of classic screens in function modules.

• When you want to make functions available to other systems, but are not able to make class methods available externally using XI server proxies. In this case, you have to use function modules.

Detailed information is available under ABAP Objects [Extern].

4.2.1 Why You Should Use ABAP Objects

Object-Based Programming with ABAP Objects - Advantages If you design your code on an object basis using ABAP Objects, you have a range of advantages: ...

1. Too much global data can be a major source of error in programming. ABAP Objects enable you to hold data locally within a class or an object, and to expose only data to the outside that is actually needed there. Ideally, you provide access using Get and Set methods. These prevent internal data from being changed without authorization.

2. Writing maintainable code means that you do without copying code. Object-based programming provides the option of inheritance. If you require a class with similar semantic properties as a class that you already have, then you inherit from this class and overwrite the respective methods. A typical example is the following: You require a TRUCK class and already have the general class CAR. This class needs certain attributes that are not contained in the class CAR, such as LOADAREA, LOADVOLUME, WEIGHT. You can adopt methods such as ACCELERATE and STEER from the CAR class. The methods BRAKE and CALCULATE_BRAKING_DISTANCE would have to be re-implemented for trucks compared with the class CAR because trucks have a more effective braking system than cars.

3. Thanks to the linking of data and methods in objects, you can work with units that hold your statuses. You also have the assurance that data is processed only with the intended methods.

Page 24: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 19

4. Working with independent interfaces has a major advantage when it comes to separating the interface from the implementation. In this way, you can easily change the implementation or replace an object with another one, without changing the access – as long as the new object implements the required interface.

5. A flexible coupling mechanism, based on the “publish and subscribe” model, makes for a far more flexible program flow than static procedure calls. In the case of ABAP Objects, you achieve this with events to which other methods can subscribe. In this case, they will be called whenever the corresponding event occurs.

What Else Does ABAP Objects Offer? Even if you do not wish to avail of the advantages of object-based programming, there are good reasons for using ABAP Objects all the same. ...

1. Procedural ABAP links the calling of certain program parts to events in the runtime environment, depending on the program type. This is an advantage as long as you wish to remain in the framework provided for a report, for example, and as long as you know as much about the sequence of events and what the respective consequence of an event is. This is a complex situation. It becomes even more complex through the fact that the consequence of messages of the same type are always different – depending on the event block in which the control flow is currently located.

If you do not view yourself as an expert for the events of the runtime environment, it would be better for you to use ABAP Objects. In this case, you do not have to know a great deal about implicit processes running in the background, but only about the basic concepts of ABAP Objects. Therefore, use ABAP Objects to get more explicit control on program flow in a far more simple setting.

2. To remain downward compatible, a number of statements that have now become obsolete are still allowed in procedural ABAP. In ABAP Objects, the syntax checks are much stricter: Many old statements are prohibited, many previously implicit syntax declarations must now be explicit, operations that could potentially cause errors, such as ADD-CORRESPONDING, are now no longer allowed. The use of ABAP Objects forces you into a more precise, more explicit kind of syntax that avoids errors. Using ABAP Objects you get a more stringent syntax check.

3. The new ABAP technology is programmed in ABAP Objects. Also, the user interfaces of the new ABAP technology are implemented on an object basis. This means: If you wish to use these new ABAP technologies, you must use the classes in which the respective features are implemented. Examples of this are shared objects, runtime type services, or object-oriented exceptions.

The Limits of ABAP Objects You should use function calls only where they are absolutely necessary.

• If you wish to encapsulate a classical screen, you require function modules. A class pool cannot have any screens as components.

• Classic access through RFC is only possible using function modules. You can generate server-side proxies for ABAP classes using XI and thus provide existing functions as external services in classes. However, function modules are still a better choice in comparison in order to make the functions accessible as a Web service or using RFC.

For the modularization of your program, you should use class methods - provided you do not require multiple instantiation. Use these class methods instead of subroutines. The parameter interface for subroutines is not as sophisticated as for methods. The interface parameters for subroutines are positional while those of methods are keyword parameters.

Page 25: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 20

4.2.2 Using ABAP Objects - Best Practices Program as defensively as possible: Access to the elements of classes should be as restrictive as possible and exceptions should only be made in individual, justified cases. The less code you expose to the outside, the more freedom you have for adapting or optimizing the implementation of your classes to suit your needs.

• Declare classes as FINAL.

• If working with public attributes, declare them as READ-ONLY.

• Keep the number of public attributes to a minimum.

• Any methods that can be private should also be declared as such.

• For internal services, use local classes in class pools. In the case of self-contained services, this is preferable to private methods of a global class.

• Use inheritance sparingly. If you are unsure, use interfaces to achieve polymorphism.

• It is better to use instance methods in local singletons than class methods: In this way, you can control instantiation and lifetime.

• If you require loose coupling, use events. Do not try to implement it yourself.

• Limit the lifetime of your variables, as much as the relevant program allows. Local variables have a shorter lifetime than instance variables, which in turn are more short-lived than class variables.

4.3 Sharing Data

The Problem Reading data from the database into an ABAP program affects the performance of the central database and, as with any other database access, there is a certain amount of effort involved. Furthermore, accessing the database via the network also requires time. In other words, database accesses are performance-intensive in many respects. Therefore, it would be a more attractive option to load the data into a common memory area a single time, for it then to be centrally available to several programs or users.

The Solution until 6.40 and Its Disadvantages Up to Release 6.40 of the SAP NW Application Server, data exchange within and outwith the boundaries of internal sessions was carried out by means of imports into or exports out of the cross-transaction application buffer of the shared memory.

The disadvantage of the classic import/export solution is that the data must first be loaded from the database into an internal session and exported into the cross-transaction application buffer of the shared memory. If any other internal sessions want to work with this data, they have to import it from the shared memory and then process it in their internal sessions. This is extremely copy- and memory-intensive.

The Solution as of 6.40: ABAP Shared Objects As of Release 6.40, there is a better solution to the problem of how to make the same data available to multiple internal sessions within the SAP NW Application Server efficiently: shared objects. This enables you to load the data directly from a data source – for example, the database or RFC – into the shared objects memory and aggregate it there at a central location. The data can then be used by different users without them first having to load and

Page 26: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 21

aggregate it or copy it from the cross-transaction application buffer of the shared memory into their internal sessions.

Detailed information is available under ABAP - Shared Objects [Extern].

4.3.1 Shared Objects - Basic Features

Use Cases for Shared Objects With ABAP shared objects, you can implements a buffer between multiple users or an exclusive buffer for a single user..

From a technical point of view, using shared objects memory for a shared buffer is only possible under the following conditions:

• The buffer has a low update frequency (from once a day to once per hour)

• It is used for large datasets

• It is used by one writer and many parallel readers

The shared buffer is comparable to a catalog in that it is created at one position, read by many, updated at relatively large intervals, and its individual contents can be quite substantial.

Technical Implementation of Shared Objects Technically, the shared objects memory is part of the shared memory, which can be configured using profile parameters. It consists of shared objects areas, which are created at design time with the shared objects area manager (transaction SHMA) and identified with unique names. These areas are instances of which you can, at runtime, create instances with names that are unique area-wide. You store the user data in these instances for it to be available server-wide.

You can create class instances for your user data directly in the shared memory. All objects can be accessed via the relevant root object of the instance. The shared objects area monitor (transaction SHMM) provides an overview of the areas, instances, locks, and versions of a shared objects memory.

Lock Concept There is also a rough lock concept for shared objects areas, which is intended for the central use case of the catalog with one writer and many readers. You can only apply read, write, or update locks to complete areas. Multiple parallel read locks are possible, write locks are exclusive. Lock requests are either immediately granted or the relevant exception is raised. Only one read lock per internal session is possible for the same area instance.

Versioning A shared objects area should, when necessary, always be available. If so desired, you should be able to ensure that a shared objects area can always be read, even while this area is being updated. In these cases, you can activate versioning for an area.

While a new version is created in the background, the readers remain connected to the old version. Once the new version is finished, it becomes the active version and the old version is then obsolete. New readers are then connected to the new, active version. As long as any users are still reading the old version, it remains intact. Once the last reader of the obsolete

Page 27: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 22

version has closed his connection, this version is flagged accordingly and deleted by the garbage collector.

4.3.2 Shared Objects - Advanced Features

MULTI_ATTACH – Avoiding Two-Way Blocking When programs from two different internal sessions require several exclusive locks, it is easy for deadlocks to arise.

Two programs A and B in different internal sessions both attempt to obtain exclusive locks for the areas 1 and 2; each does so in a different order. This results in the following situation: While program A obtains the lock for area 1 and holds it until it also gets the lock for area 2, program B waits for the lock for area 1, which program A already has, and itself holds the lock for area 2, which program is waiting for. Programs A and B would thus continue to block one another.

The MULTI_ATTACH method prevents such situations: You must use this method if you want to connect to more than one area from an internal session. This method then ensures that you either obtain all the required locks or none of them – that is, a non-atomic operation is made atomic. In this way, you will never hold one or more locks while waiting for others.

Synchronizing Shared Objects Areas and the Database In some cases, you have to ensure that the data in shared object areas is synchronized with data on the database. If you connect to an area, change the data there with DETACH_COMMIT, and the changes to the relevant database data then fails and a rollback takes place, this would result in inconsistencies between the data on the database on that in the shared objects area.

In these cases, you should use transactional areas. If you use the DETACH_COMMIT command here, any changes to data in the transactional area only come into effect at the next database commit. Until then, the changes are deferred.

Making Changes in Shared Object Areas Available Server-Wide By making the appropriate settings for the framework, you can make data from one area of a server available on other servers of the same system. Once the data is changed on one server, the other servers are informed that this area was invalidated.

You must then make sure that an area constructor for automatic area building is called in the case of any read requests to an invalidated area. The framework supports you in that changes to areas are propagated over multiple servers.

Automatic Area Building You can also specify that this automatic area build take place if no active instance of an area exists when a read request takes place.

Lifetime and Displacement of Shared Object Areas At design time, you can set the lifetime of the contents of a shared objects memory area using transaction SHMA:

• Up to a specified time at which the contents are deleted

• Up to a specified time at which the contents are reloaded

Page 28: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 23

• Until a specified time has passed without any read accesses taking place

• Unlimited – that is, until the application server is shut down or the area is explicitly invalidated

You can also define that specific areas are to be displaced if the memory for all areas, which you defined, or the total memory for one area is exceeded.

Client Dependency At design time, you can specify that shared object areas are to be client-specific. This means that every client sees only its instances.

4.3.3 Best Practices You should communicate with the areas via a broker. This means, you should use a class that encapsulates the following:

• Area structure

• Area access

• Lock management

• Authorization checks

4.4 Exception Handling As you will know, it is always possible that errors may occur in a program. Some errors are so severe that it is no longer possible or useful to continue the normal program flow. However, you can write your program in such a way that it reacts to such situations appropriately. In modern programming languages, there is a concept that deals with these situations, namely exception handling.

ABAP features a class-based exception concept. It is similar to the corresponding concept in Java, but offers the user more flexibility in a number of aspects. When you write new code, you should only use the new class-based exceptions for error handling.

Detailed information is available under Exception Handling [Extern].

4.4.1 Class-Based Exceptions in ABAP To understand the benefit of this concept, think about what you expect from effective exception handling:

• On the one hand, the control flow should be adapted to the new situation – that is, continue program execution, if possible, at the best possible place with regard to the error.

• Furthermore, information about the error should be provided, so that it is clear at runtime (or later) what happened and why.

In ABAP, class-based exceptions are objects of special exception classes. Each of these classes represents a specific error type. The process of raising an exception consists of

Page 29: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 24

instantiating such an exception object and changing the control flow at the same time. There are system exception classes, which represent system error types like the class CX_SY_ZERO_DIVIDE (division by zero), and exception classes, which the user can create himself. Technically, there is no difference between the two types. All exception classes, whether defined by the system or the user, inherit from the class CX_ROOT.

4.4.2 Basic Features

Exceptions and the Control Flow When an exception is raised using RAISE EXCEPTION, the runtime environment immediately searches for a suitable handler, first in the procedure (that is, a modularization unit such as a subroutine, method, or function module) where the error occurred and then further up in the call hierarchy. Once a suitable handler is found, the control flow branches to that location and processes the code of the handler before continuing. If no handler can be found, the program ends with a short dump.

Passing Information in the Case of Exceptions An exception object can contain translatable, parameterized texts, whose parameters are substituted at runtime. These texts should contain information about the error, which should be suitable for the relevant recipient. If it is a programmer, you can use a technical error description. However, if the error information is intended for end users, you should avoid messages such as "Severe error at memory location 1FA359. Do you want to debug?" and use a text that the end user can understand, for example “No database access”.

Protected Area: TRY-ENDTRY You can only handle an exception in an ABAP program if it is raised in a protected area. This is the area between TRY and the handlers within a TRY-ENDTRY structure. The handlers themselves are not part of the protected area.

Page 30: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 25

4.4.3 Planning Exception Handling and Delegating Exceptions

Catching and Handling Exceptions A TRY-ENDTRY structure can contain several handlers and you can catch exceptions of different classes in a handler. Furthermore, with the exceptions of a class, you can also catch all exceptions of any subclasses of this class. In this way, exceptions can be handled in groups. For example, you can decide to raise different exceptions depending on whether a specific customer address exists, is invalid, or exists multiple times, but then assign all these exceptions to a common superclass and catch the superclass.

You catch exceptions using a CATCH structure that contains the name of the relevant exception class or a class higher up in the inheritance hierarchy. You can handle exceptions that have been caught. Handlers should be implemented so that they react to errors accordingly and ensure that the program can continue to run correctly. However, in a modularized program, this is not always possible at the point where the exception was raised.

Delegating Exception Handling Let us imagine you want to write a service class that manages address data on the database. A method receives the key of a specific business object and is to read the relevant data from the database. If no address is found, you should raise an exception, but it should not be handled immediately in your method. Not that this would be possible anyway. You do not know what the caller intends to do with the address, that is, whether it is just additional information – for example, for the agents of a call center – or whether the program flow would have to be significantly changed without this data – for example, in the case of a delivery, for which a delivery address is essential.

Declaring Exceptions at the Interface For this reason, it is important that you, as a developer of modularized units, can delegate exceptions to the caller. The process of passing exceptions up the call hierarchy, known as propagation, occurs automatically whenever an exception is not handled in the TRY-ENDTRY structure in which it was raised. However, the exceptions must be declared at the interface of a procedure (method, subroutine, function module). Otherwise syntax errors will occur at design time and the exception CX_SY_NO_HANDLER will be raised at runtime. In this way, the runtime environment ensures that only declared exceptions can exit a procedure (special exceptions to this rule will be covered later).

Why do exceptions have to be declared? The caller of a method has to know what exceptions to expect. The caller is not usually interested in the inner workings of the called method and the methods called there concern the caller even less. The declaration at the interface ensures that you, as the caller of a procedure, can be certain about which exceptions you must handle and which you must pass on.

CLEANUP Block If you do not handle an exception in your program unit, and the control flow jumps from the raised location up to a point in the call hierarchy where it can be handled, the program unit may be left in an inconsistent state and some resources may be overloaded. The CLEANUP block is intended for such situations. The CLEANUP block of a TRY-ENDTRY structure is only processed if:

• The exception is raised in the protected area of this structure

Page 31: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 26

• The exception is not handled in this structure, but there is a handler further up in the call hierarchy. If the exception is not caught anywhere, it is important not to erase any traces of the error. Therefore, the CLEANUP block is not processed in these cases.

Under no circumstances should you attempt to exit a CLEANUP block prematurely using RETURN, EXIT, or CONTINUE. The CLEANUP block is processed on the basis of the confirmation that the error is handled further up the hierarchy. Leaving it prematurely could result in this confirmation being violated. Therefore, a runtime error is triggered if you attempt to exit a CLEANUP block prematurely.

Planning Exception Handling Locally If you are writing reusable software, you should only plan the exception handling for the program unit you are writing. You should, as much as possible, avoid making specific assumptions about the calling layers or those that you call, if these assumptions go beyond the scope of the contract specified in the interface. The implementation of these layers could change, and then your exception handling may no longer function correctly if it depended on assumptions about the inner workings of these layers and these assumptions no longer exist at a later stage.

You should simply decide the following for your procedure: Which of the exceptions that you raise or receive from lower down the hierarchy do you want to handle and which do you want to delegate, that is, propagate. When you handle exceptions, you have to be particularly careful with messages or other means of passing information to the user interface. Avoid it if you are not completely sure that your program unit makes up the user interface.

Handlers You handle an exception in a handler, of course. However, your actions in each case can be very different. An analogy to an interrupted journey may help to clarify what appropriate exception handling involves. Imagine you are unable to continue along your travel route, because a bridge across a river is closed. This represents the error situation. There are different ways of reacting:

• You can use a different bridge and still reach your goal despite taking a detour. The analogy in the case of the program would be to recalculate required values in a cache.

• You can abort your day trip and continue with what you had planned for the next day. If an ERP application cannot continue listing a delivery because the price of a product is missing, the control flow of the program can simply move on to the next product.

• If there is no other bridge to be found and the rest of your journey is not possible as you cannot cross the river, you may decide to abort the entire trip. This can be compared to the case where an error in the program flow is so severe that it would be best to stop the program.

There is one task you will often carry out in the handler for which there is no equivalent in this analogy: Sometimes, an exception is raised with a very technical text and you want to pass this exception up the call hierarchy, but here a text is required that the end user can understand. In this case, you catch the original exception, raise a new one that the end user can understand, and attach a reference to the old exception to the new exception as an attribute. This is known as mapping one exception onto another.

You should only pass information about an exception to the user if you are completely sure that the component you are writing is in a suitable layer. If your component is called far away from the user interface, passing a text directly to the user in the case of an exception would not be advisable. Instead, you could handle the technical side of the exception and delegate an exception with a new text further up the hierarchy.

Page 32: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 27

4.4.4 The Three Exception Classes in ABAP

Different Exception Classes: Motivation So far, we have been stating that all exceptions must be declared at the interface and that this is checked at design time and runtime. Indeed, this applies only to exceptions that inherit from the class CX_STATIC_CHECK.

Some errors can occur everywhere in a program – for example, resource bottlenecks. You can deal with such errors in three ways:

• You could declare them in each interface and in this way fill the interface with useless information.

• You could catch them locally, although there is perhaps a suitable, central handler for them further up in the call hierarchy.

• You could write empty handlers so that your program complies with the compiler check rules in this way. But this is the worst alternative. Do not take this route: If the corresponding error for which the exception is thrown actually does occur, you cannot find it.

For such general exceptions we have the class CX_NO_CHECK in ABAP. You cannot and must not declare exceptions that inherit from this class in the interface. In general, nobody can react appropriately to a resource bottleneck and handle it – unless it is very far up in the call hierarchy.

Sometimes an exception could occur, but you are sure that it could not occur in your program. This is also the case with the exception CX_SY_ZERO_DIVISION. However, you can be sure that you will not divide by zero in your program if the divisor is the result of a calculation whereby zero cannot end up being the result. In this case you do not want to handle the corresponding exception nor do you want to declare it at the interface because you can prevent its occurrence.

In such cases, the question at heart is that you can prevent a certain exception from occurring by having control over a precondition or by checking it. Therefore, it would be appropriate if – in such situations – you had the choice of checking a precondition yourself or of taking care of the corresponding exception through declaration or through exception handling. The class CX_SY_DYNAMIC_CHECK is provided for such cases.

The compiler does not perform a static check as to whether an exception of this type is handled or declared. At runtime, however, these exceptions can only leave the interface – should they still occur – if they are declared at the interface.

Overview of the Three Exception Classes There are three categories of exceptions:

CX_STATIC_CHECK: Exceptions of this class must be declared in the interface if they are not handled locally. Otherwise, the compiler issues a warning. This comparatively weak reaction is based on the fact that it would not be appropriate to invalidate an entire program because of an exception that is possibly hardly thrown at all. At runtime, the error CX_SY_NO_HANDLER is thrown in such a case. The original exception is passed as a value of the PREVIOUS attribute to the new exception. Always, only one exception can be active in a program and control the flow.

CX_DYNAMIC_CHECK: Declaration of this exception is not checked at design time. At runtime, the exception can only leave the interface if it is declared.

CX_NO_CHECK: This exception can leave a procedure whatever the case. There is no check at runtime or at design time.

Page 33: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 28

The syntax of these three exception classes is easier to understand than having a clear perception of when you should use a particular class.

When To Use CX_NO_CHECK This is the suitable exception class for exceptions that can occur almost everywhere. If you use CX_DYNAMIC_CHECK or CX_STATIC_CHECK instead, the caller of your procedure will write empty handlers or will place them in an exception of the type CX_NO_CHECK.

When To Use CX_STATIC_CHECK Choose this class if your exception can be handled appropriately by a local handler. If you choose the dynamic type, there will no longer be any guarantee that your exception will always be handled. If you choose CX_NO_CHECK, this would have the disadvantage that this exception could now occur anywhere in your program. If it actually does occur, it would be very difficult to find its origin.

When To Use CX_DYNAMIC_CHECK You use this class if someone can prevent an exception by checking a precondition. The person responsible fort his check is also responsible later on when the corresponding exception is thrown.

A typical example of this is division by zero. The person responsible for this exception is the person in the call hierarchy who makes the divisor available. If you perform a division operation and the divisor comes from your caller, you should declare the exception at the interface – while the person who supplies the divisor should check the precondition or handle the exception.

If everyone adheres to this rule, it is easy to find out who is responsible for the exception. It is the person who has forgotten to check the precondition or to declare the exception at the interface.

If you choose the static type instead, you force the declaration, although the precondition of the exception can be checked or you encourage others to write empty handlers.

4.4.5 Defining an Exception Class

The Technical Side It is extremely easy to build an exception class, from a technical point of view. In the Class Builder, you decide on an exception class and then choose from which of the three named superclasses your class is to inherit.

Under the Texts tab, you can create translatable texts in the online text repository and they are filled at runtime. Using a special method that each exception class inherits, you can access these texts. You can also create several texts for the same class and, when an exception is thrown, define which text is to be used. You can also use alternative texts in message classes for exceptions.

If you need other values, you can create as many class attributes as you wish. Always take the technical information on the exception your program needs from the attributes. Do not attempt in ay way to analyze the text off the class for this purpose.

Page 34: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 29

Semantic Considerations When Creating an Exception Class If you wish to throw an exception yourself, choose a semantic approach. This means: Go in to the syntactical details as late as possible. Do precise conceptual work first.

• Analyze the situation.

• Describe the situation in as abstract a way as possible, and with as much detail as required.

• Check whether there is already an exception class that is suitable for your purposes.

• Define a suitable exception class if you do not have one already.

Analyzing means primarily thinking whether an exception is a good idea or whether an assertion or a return code would be more suitable. Then formulate precisely the decisive features of the exception situation and extract from the position where the exception occurs because that would prevent reusability of the exception class. As soon as you have listed the decisive characteristics, check whether there is already an exception class with these features. If a class almost fits, you can add an additional text or inherit from it and definition additional attributes, should you require them.

However, never inherit from a superclass that represents a different error type from the one that your require. In some cases, it can also be a good strategy to define a more abstract exception class and then to inherit your class from this class.

4.4.6 New Exceptions and Former Concepts of Error Handling

Old Error Handling Concepts in ABAP In the classic ABAP world, up to Release 6.10/6.20, there were different means provided for dealing with error situations:

• Old ABAP exceptions, thrown through RAISE, can be handled with the EXCEPTIONS clause in the case of method and function calls.

• Certain runtime errors can be caught if the error position is in a CATCH SYSTEM-EXCEPTIONS block.

• Messages in MESSAGE statement can also display an error.

All these old concepts are being replaced by the new, class-based exception concept. In addition, the old concepts are too varying to ensure automatic mapping onto new, class-based exceptions.

Classic Exceptions in Methods and Functions Classic exceptions cannot be caught in handlers for new, class-based exceptions, and vice versa. Each procedure can only throw old or new exceptions. If you declare new exceptions at the interface in your procedure, you must map the old exceptions that you get from called procedures onto new ones. The reverse applies in the same way – if you use an old method and enhance it with a procedure call at whose interface new, class-based exceptions are declared.

Page 35: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 30

Migrating Catchable Runtime Errors For each catchable runtime error, there is now a corresponding exception class. Here, the grouping of catchable runtime errors is supported by inheritance relationships between the relevant exception classes. There are certain rules for the coexistence between old and new class-based exceptions:

• You cannot throw old and new exceptions in a procedure. If you declare a new class-based exception in the interface, you cannot throw any old exceptions in the procedure.

• You can catch all catchable runtime errors as old runtime errors using the old syntax. If you do not do this, these are automatically mapped onto the new exceptions by the runtime environment. If you have not declared these at the interface of the respective procedure, you will get the exception CX_SY_NO_HANDLER, which contains a reference to the old exception.

4.5 Developing Persistence With its three-layer architecture, the SAP NW AS is connected to a single, system-integrated database. Not only are all programs stored here, but this is also the location where various types of data are made persistent. The most important types of database storage with the SAP NW AS are:

• With database-independent Open SQL, which is integrated in ABAP, you store your data from the program in database tables and write the data in the program to internal tables, which are high-performing and enable fast search access. This method should be your first choice.

• With Object Services, selected objects are made persistent transparently, after you have defined an assignment between attributes and table columns. You should choose this method if you wish to use object-oriented programming throughout.

• With the EXEC SQL command, you can use the proprietary SQL of the integrated database, as well as open additional connections to other SAP-supported databases and access them with their SQL.

You create database tables in the ABAP Dictionary with metadata support. When you activate the objects, the database tables are created on the database. The data types are then available system-wide. For transactions, lock management, and authorization checks, the SAP NW Application Server has separate solutions, since the relevant services of the database do not meet flexibility requirements.

Detailed information is available under External Data Storage [Extern].

4.5.1 The Standard Path to Persistence

Access the Data Base Independently of Tables: Open SQL Whenever you wish to read data from the database or write data to the database, the best choice is SQL (Structured Query Language). This language has been in use since 1987 as the standard language for querying relational databases and is also the language accepted as the ISO standard. You can integrate SQL statements into the ABAP program. Contrary to what you are used to from programming with Java, you do not need to use a manager to start a connection with a database and then return or close it in a pool.

Page 36: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 31

Based on the architecture of the SAP system, you always have an open connection to the integrated database at your disposal. Here the SAP NW Application Server supports the standard databases beyond normal levels. This means that you can program database accesses independently of the manufacture type and do not have to write different code for the different databases. This would involve a lot of effort and would require code modifications in the case of porting.

With the SAP NW AS, you can program your database accesses in the Open SQL of SAP – independently of the proprietary specifications of the database your system works with. This is not always to be taken for granted. SQL is the standard language for querying relational databases. But, in effect, each database producer uses its own proprietary variant of SQL that works with different manufacturer-dependent SQL statements.

One important service of the SAP NW AS is that you, as a programmer, do not have to take care of these differences and your ABAP program can still work with the databases of different producers. The SAP NW AS uses Open SQL. This is a subset of the manufacturer-dependent SQL statements, plus other statements that go beyond the standard range of manufacturer-dependent SQL commands.

Indeed, the database interface hides all the manufacturer-dependent details from you. You write all SQL statements in one language – irrespective of which database the system is connected to. You enter statements in Open SQL simply as lines in your program so that the syntax of these lines can be checked already at compiling time. You can write the results of the queries into data objects of the ABAP program and, conversely, you can write the values of these data objects to database tables.

Declaring Database Tables on a Metalanguage Basis: The ABAP Dictionary So far, we only talked about the fact that you can read and write data using Open SQL. You will rightly ask what command you can use to create and manage database tables. Naturally, you can create a database table using the SAP NW Application Server. But you do not do this with code within your program, but declaratively.

In the ABAP Dictionary, you define database tables and define the properties you need.

• Do you wish to have the row type of the table so that it can be enhanced or not? Or in other words: Should it be possible later on to add further fields to the row type?

• Which size should the database table have? This actually means how many data records are to be stored there later on?

• Is the database table to be buffered, and if so, in which way?

Here you must revert to the built-in database types of the Dictionary for the types of the individual database fields or, when reverting to these types, you define yourself your own more complex semantic types. You wish to create a table for address data, for example. For this, you require – in the first step – the fields STREET, HOUSE_NUMBER, CITY, ZIP CODE, and so on. You must declare these also as data fields in the ABAP Dictionary.

So you enter the metadata of the fields and the tables you require in the ABAP Dictionary. As soon as you activate the table and the fields, the table is created in the database and the fields are available system-wide. The advantages of this approach – crate data objects as declarations – are very clear.

• The database tables are available for transports to another system as soon as the respective, transported ABAP Dictionary objects are activated. If you were to declare the tables in the program it would require more effort and would be more awkward to determine the time as of which they are available in another system.

• The declarative options of the ABAP Dictionary provide you with features that reach beyond the options available in SQL in this regard.

Page 37: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 32

• In the case of SQL queries, the system can easily check whether the queried tables exist.

• In addition, that part of SQL with which you create and manage tables is implemented by the respective database manufacturers in a more proprietary fashion than that part of the language with which you write and read data.

Editing Mass Data with Good Performance – Open SQL and Internal Tables Occasionally, you will require only one particular data record. Or you wish to read a certain set of data with certain properties from the database and edit this further in your program. In this case, you can see how ABAP is ideally optimized for the requirements of business programming. You can write the entire result set of an SQL statement into one data object of the internal table type.

An internal table – you must remember – has important properties in common with database tables. It is define by its row type and the key. In contrast to database tables, internal tables – as the name suggests – are located in internal mode of the respective ABAP program. The third defining feature is the table type, which defines whether the table is sorted, unsorted, or a Hash table. The fact that they are dynamic data objects makes internal tables so practical for the user. The number of rows adapts itself dynamically and is not defined in the declaration.

The internal table, therefore, should be your first choice for the set of data selected by your SELECT statement or for the data you want to write to the database. In particular, you should remember that you can use internal tables not only for looping – as you are used to in collections in Java – but you can also use ABAP commands to search in internal tables for data records that meet certain requirements. Using internal tables you hold the individual business objects of the same type in an internal table with this row type.

4.5.2 Other Persistence Options

Object-Relational Persistence - Object Services Despite all the convenience and optimization possibilities of internal tables, there are cases where you will want to resort to alternatives: Internal tables represent a break in the object-oriented program paradigm. If you strictly adhere to it, your business objects will correspond to objects of your program, while the attributes will correspond to elements of the structure of the relevant business object.

Sometimes you will want to use object-oriented programming throughout. In these cases, it would be inconvenient if you were forced to use classic programming in the methods themselves – that is, store your objects at the end by means of classic programming. It would be preferable if data and methods encapsulated in an object could also be stored together – that is, store the object along with the information as to which class it belongs to. In this way, when an object is loaded from the database, the methods of its class are also made available. A different program could then continue working with the object in the state in which it was stored by another program.

For this purpose, ABAP provides the Object Services, whose role is comparable to that of JDO in Java. The ABAP Object Services form a layer between the ABAP program and the database, which ensures that the ABAP objects are stored on the database under a unique identity and can also be reloaded. You can also run queries, which correspond to selects in SQL, for objects in the database and get references to a set of objects that matches your search criteria. If you create a persistent object in a program and that object already exists in

Page 38: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 33

the database, it initially has the status of the data in the database. Changes to the object are only written back to the database if directly requested.

Do not use your own mechanisms to make objects persistent, but use the system services instead. The option of serializing the objects yourself and storing them on the database in byte buffers is only to be used when you want to store a small amount of data for a short period during program execution. With regard to access, search, and selection possibilities, the restrictions resulting from these self-serialized objects mean that this option is not useful for long-term storage or larger amounts of data.

Proprietary Addressing of Databases – Native SQL With Native SQL you can use database-specific SQL statements in an ABAP program. In this way, you can include database tables that are not managed by the ABAP Dictionary and thus address datasets that were created independently of SAP NW AS ABAP. You start a Native SQL statement with EXEC SQL and close it with ENDEXEC.

Native SQL allows you to execute (nearly) all statements available through the SQL programming interface (usually known as SQL Call Interface or similar) for executing SQL program code directly (using EXEC IMMEDIATE or a similar command).

Since a Native SQL statement largely bypasses the database interface, you do not have access to some services that would be available with Open SQL: No table logging takes place, nor is there any synchronization with the database buffer on the application server. For this reason, you should, wherever possible, use Open SQL to change database tables declared in the ABAP Dictionary.

To ensure consistent behavior of transactions, you should not use any statements to control transaction processing (COMMIT, ROLLBACK, ...) with Native SQL.

4.5.3 All or Nothing – Database and SAP Transactions If you are writing business programs, you are dependent on having certain program parts executed in full or not at all. If the program, for example, debits money on one account and credits money on another, it must not happen that the money is deducted from the one account and not credited on the other. If problems occur during this procedure, it must be ensured that these related postings are executed either in full or that none of them is executed.. This would mean that, in the latter case mentioned above, postings already executed would have to be reset entirely.

Processes of this nature are generally called transactions. At the end of a transaction, it is confirmed and posted in its entirety to the database (COMMIT) or discarded in its entirety (ROLLBACK). One could assume that the SAP program can access the transaction handling process of the database. However, this is hardly possible. A business transaction may extend over several screens. It is not certain that a program works with the same work process over several screens. On the contrary, it is the feature of the SAP NW AS that it can work with much less work processes than users. If a program is just waiting for inputs, its work process so far can be passed to another user. A program can work with different work processes, one after the other, and a work process can be used by different programs, one after the other.

Database transactions, however, cannot cover several work processes. If a work process changes its owner, the database transaction with which it was linked must be committed or rolled back. A typical ABAP application program can work with several different work processes, one after the other. Therefore, the SAP NW application server has its own transaction concept. The Open SQL statements INSERT, UPDATE, MODIFY, and DELETE allow you to program database changes that extend over several dialog steps. But even if you have not explicitly programmed a database commit, the implicit database commit that occurs after a screen has been processed concludes the database transaction.

Page 39: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 34

The solution to this problem is to combine all the update postings of a program using function modules. If you call a function module using the statement CALL FUNCTION ... IN UPDATE TASK, the function module is flagged for execution using a special update work process. The actual execution of the function module is postponed therefore. This means that you can write the Open SQL statements for the database changes in the function module instead of in your program, and call the function module at the point in the program where you would otherwise have included the statements. When you call a function module using the IN UPDATE TASK addition, it and its interface parameters are stored as a log entry in a special database table called VBLOG. You can then commit or roll back all the update postings of a program in one go.

If you work with the Object Services, you do not have to take care of transaction handling. Changes to persistent objects are written to the database by the Object Services, using update posting function modules – provided you set a Commit. For this purpose, you can use either the regular COMMIT WORK, or you can use the transaction service for object-based wrapping of transaction control. The transaction service provides you with the option – as an additional feature – of nesting transactions to as deep a level as you wish and rolling back changes to inner transactions without the outer transactions being affected by them.

4.5.4 Exclusive Database Access - Lock Concept of the SAP NW AS

For some database accesses, you must ensure that your program has exclusive access to this data for a specific time period. This is the only way to avoid another user working with the data while you are changing it. For example, it must be impossible for the situation to arise where two users both sell the last flight. The solution to this problem is a lock concept. Just as the SAP NW Application Server has its own transaction concept, it also has its own lock concept. The granularity of the database locks is not very fine and they are also not flexible enough. Locks should also remain in place for the duration of database transactions and SAP transactions. The SAP locks work with logical lock objects. Lock objects allow you to set SAP locks for entire application objects. An application object consists of one or more data records in a database table, or several data records from multiple database tables that are linked using foreign key relationships.

Before you can use a lock object, you must create it in the ABAP Workbench. A lock object definition contains the database tables and their key fields on the basis of which you want to set a lock. When you create a lock object, the system automatically generates two function modules with the names ENQUEUE_Name and DEQUEUE_Name. You can then set and release SAP locks in your ABAP program by calling these function modules in a CALL FUNCTION statement.

These function modules are executed in a special enqueue process, which exists only once system-wide. The enqueue function module sets an SAP lock by writing entries in the central lock table. If the lock cannot be set because the application object (or a part of it) is already locked, the function module informs the user. The following figure shows the components involved in the lock process:

Page 40: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 35

...Dialog

WPDialog

WP

...Enqeue

WP

Dispatcher

...SAP GUI

...

SAP GUI

Dispatcher

ApplicationServer 1

ApplicationServer 2

Database Management System

Application Data

EnqueueTable

SAP locks are logical locks:

• The effectiveness of the locks depends on cooperative application programming: Since no physical locks are set in the database tables themselves, all programs that use the same application objects must query the central table for any locks explicitly. There is no mechanism that automatically prevents a program from ignoring the locks in the lock table. An SAP lock is thus like a traffic light, not like a barrier.

• A locked data record is not physically locked in the database table.

• A locked data record does not have to physically exist in a database table.

4.5.5 Restricting Access - Authorization Concept of the SAP NW AS

Not every user is to be able to execute all functions, nor is everybody to be able to see or change any data on the database. Therefore, it is necessary to restrict access to data. The SAP NW Application Server does not use the authorization checks of the database for this. An SQL command in an ABAP program does not trigger an authorization check in the database system and you can thus, in principle, access any data on the database using Open SQL or Native SQL statements.

The SAP NW Application Server has its own technique for ensuring that you can restrict access to data as required. This is necessary firstly because the entire SAP Application Server works on the database with a single user. Secondly, the granularity of the mechanisms provided by the database is not fine enough for SAP requirements.

The basic concept in the SAP NW Application Server is that specific authorizations are assigned to users in their master data (transaction PFCG). In actual fact, authorizations are grouped into (composite) roles or profiles, which are then assigned to users, but that is irrelevant with regard to the basic concept.

Page 41: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 36

In a program, you can then check whether a user has a specific authorization. If yes, the return code SY-SUBRC has the value 0, otherwise it does not. Authorizations are always instances of authorization objects. An authorization objects has up to 10 fields and serves as a template for the possible instances and combinations of the relevant authorizations. The large number of authorization fields is required so that authorizations can be instantiated with very fine granularity. For example, a user is to be able to see all data for Lufthansa flights, but not that of any other airlines, while another user is able to change the data. You create authorization objects in transaction SU21 after creating reusable authorization fields in transaction SU20.

In general, you enter a Dictionary reference for the authorization field input help. For example, if you use the Dictionary table T001 for a company code field, this ensures that only valid company codes are suggested as possible values when managing authorizations.

The same applies to authorizations or authorization objects and their fields. Note that the sole purpose of the used Dictionary objects is to ensure the fine granularity of the check and to specify what is to be checked and thus happen in the program if the check is successful.

The authorization check for fields of the table SPFLI, for instance, knows nothing about what happens in the program after a successful check. As a programmer, you must make sure that what happens in a program after an authorization check is precisely what was queried in the check. There is no automatic procedure in a program that checks, for example, that no MM data is displayed after a CO object query in your program. However, there is also no mechanism to prevent you naming a program for customer display “Schedule Creation”, for example.

Authorizations are comparable to keys that are assigned to users. There are locks at specific points in the program, and only users with the correct keys can open these. The key types – such as car, house, or bicycle keys – correspond to the various authorization objects, while individual keys correspond to the different authorizations, the position of the notches on the keys to the fields of the authorization objects, and the form of the notches to the field values. A bunch of keys is comparable to a role.

Since authorization checks can be very complex, it is a good idea to encapsulate them away from application programmers. For example, you could store your SQL query in a method, which in turn calls a further method that executes an authorization check before the actual SQL call takes place. In this case however, the programmer of the method that checks the authorization and the developer of the database query have to work together closely.

As described above, you can only check authorizations properly if you know what is to happen in the program in the case of a successful or failed check. With regard to the creation of a program, we now turn to the important question of what happens if the check fails. If you incorporate authorization checks in a program, the reaction to a successful check is generally already clear. However, you still have to consider how the program is to respond if the authorization check should fail. In such cases, the program could display and error message or write a log. Another option is to make a specific function – for example, displaying detailed data – unavailable to the user and to do so without comment.

You should also take into account that it is better to include your authorization check as early as possible in the program flow, both for performance and usability reasons. For example, it would be pointless to carry out a range of preparations for an SQL query if the user has no authorization for this query anyway. A good way of dealing with cases like this is to not display specific buttons or menu entries for users without the relevant authorization.

Page 42: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 37

4.6 Using Connectivity and Interoperability Web services represent the strategy for communication within NetWeaver and between other systems. They are a uniform technology that allows you provide and consume services independently of implementation and the underlying protocol. Furthermore, you can do so both within NetWeaver and in the communication with other systems.

In addition, the Exchange Infrastructure provides:

• An infrastructure for the XML-based exchange of messages

• A tool for defining new integration scenarios and managing all information relevant to the integration

• The possibility of obtaining business process and integration knowledge from SAP in the form of predefined scenarios

• Mapping of data and structures

• Message routing at runtime

• Different adapters for connecting non-SAP systems and technologies

• Central management of all interfaces

• Simple enhancement possibilities of interfaces

The Exchange Infrastructure and Web services make up two sides to the SAP strategy of supporting a service-oriented architecture.

Detailed information is available under Web Services [Extern].

4.6.1 The Integration Strategy of SAP and Web Services

Integration Between Different Systems Business processes reach beyond system borders. This means that, as a developer of business programs, you often work with scenarios that cover several systems at one time. Therefore, it is necessary to be able to address functions – also called services – in another system or, viewed from another perspective, to be able to provide functions for other systems. The strategy in this case is to provide the desired function as a Web service and to consume it on the client side as a Web service.

Web Services as Integration Strategy Web services represent a communications strategy to be used within SAP NetWeaver as well as a strategy to or from an external source. This integration technology is based on open standards. With it, you can include existing functions – irrespective of whether they are implemented. You can also provide new functions as a service and then access them from other systems. Within the SAP world, you can provide BAPIs, RFC modules, Java classes, Enterprise Java Beans, as well as Idocs and XI server proxies as Web services. You can, of course, consume Web services from external systems also – regardless of the implementation supporting them.

What Are Web Services? A Web service is a modularized function that can be executed independently. You can call a Web service from any system using a standardized protocol. We distinguish between the Web service provider – a server that provides certain services – and the Web service

Page 43: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 38

consumer, who consumes certain services as a client. When you call a Web service, you pass on input parameters and the data is returned to you in output form.

4.6.2 How Web Services Function

The Central Concepts The SAP NW Application Server supports the providing and consuming of Web Services. It does this using Web Services standards: XML, SOAP, the Web Service Definition Language (WSDL), and Universal Description, Discovery, and Integration (UDDI).

SOAP is a general format for XML messages. Different transport protocols can be included in this format. Using WSDL, you describe the actual interface of your Web service, which consists of method names and input and output messages. At runtime, the message are packed using SOAP and transferred in this form.

UDDI is a type of address service for Web Services. There you will find published the basic data you need to call a Web service. As a Web service provider, you can publish your services there.

SAP AG 2004, SAP TechEd / Session NW106 / 7

Stan

dard

Inte

rfac

es

Providing Web Services based on Open StandardsVi

rtua

l Int

erfa

ce

Bus

ines

s A

pplic

atio

nIDOC

BAPI

RFC

EJB

Java Class

XI Server Proxy

Web ServiceRuntime

Web ServiceMeta Data

Development Environment

SAP NW Application Server

WSClient

… ……

UDDIUDDI

Registry

SOAP

WSDL

Web

Ser

vice

Providing and Consuming Functions as Web Services If you wish to provide a certain function written in ABAP as a Web service, you can wrap this using a Web service. This is the so-called inside-out approach. With it, you can make an

Page 44: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 39

existing standard interface (for example, a function module) accessible as a Web service using tools and wizards.

If you wish to call a Web service from within an ABAP program, you can also have a proxy class created using the tools on the basis of the WSDL description of the respective Web service. It is of no significance how the Web service was implemented on the server side. The client proxy takes care of the technical aspects – such as creating a SOAP message, the transport layer, or security settings. It encapsulates the communication therefore. The developer of the client application can thus concentrate on the creation of business functions.

SAP AG 2004, SAP TechEd / Session NW106 / 1

Web

Ser

vice

Prox

yConsuming Web Services based on Open Standards

Web

Ser

vice

Clie

nt

App

licat

ion

Web ServiceRuntime

Web ServiceMeta Data

SAP NW Application Server

UDDIUDDIRegistry

Development Environment

SOAP

WSDL

Web Service Provider

Bus. Functionality

Web

Ser

vice

Here you can provide one and the same function in different Web services. Web services provide implementation abstraction through the concept of virtual interfaces. This means that. for a Web service, you fill certain input parameters of a function with default values and, in another Web service, provide the same function with all its parameters. For example, the customer of a Web shop for a textile manufacturer does not wish to be bothered with internal posting details for his or her order. In such a case, the Web service solution would be to fill certain parameters – for example, the company code – with default values already on the Web service provider side, and to provide the Web service client only with parameters that he or she can actually specify. A department store, on the other hand, would like to provide its order with the same manufacturer with a wider range of business posting data. The Web service with all input values for the function behind it has been designed for this purpose.

Page 45: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 40

4.6.3 Generating Interfaces and Proxies – The Outside-In Approach

A second approach for providing services is the outside-in approach. Outside-in means that you create the metadata of your interface on a business level in the integration repository of the exchange infrastructure. Here you define global data with a technical data type and semantics that define the content of the data. For example, a global data type could define an address. This data is pure metadata.

In the next step, use transaction SPROXY to access this metadata in a back-end system – for example, in the ABAP page of the SAP NW Application Server. Then create a server-side proxy on this basis. After you have generated your interface on the provider side, you can start to develop its functions. The more frequent case is probably that you use your generated server-side proxy to call only methods and functions modules that already exist (glue implementation). Viewed in this way, it is also possible to use the outside-in approach to wrap one or several functions that already exist on the ABAP side with a new, common interface and a server-side proxy class. This class then calls the respective functions. To access the proxy created in this manner, generate a client-side proxy in the calling system in the respective program – again using transaction SPROXY. This proxy provides a suitable interface and encapsulates communication.

In this way, you can provide and consume Web services with the support of tools with the NW Application Server and this without any great effort. You can wrap an existing standard interface with a Web service without problems and thus make it accessible as a service. For the outside-in approach, which you can use to provide methods of ABAP classes or objects as services (also applies to Java classes), you require the exchange infrastructure. This is also a part of SAP NetWeaver.

4.6.4 XML-Based Process Integration with the Exchange Infrastructure

By enabling you to generate outside-in interfaces, the Exchange Infrastructure provides a number of additional functions on the basis of XML-based messages:

• You can manage the technical and semantic metadata of your interfaces centrally and landscape-wide.

• You have a hub structure for your messaging and not an excessive amount of point-to-point connections.

• If required by the mass data exchange for performance reasons, you can also create point-to-point connections via the Exchange Infrastructure.

• Since the interface data is available centrally, you can manage any changes more easily.

• You can define mappings between data and structures of different technical and semantic types and execute them at runtime.

• You can specify the destination system of a message according to various different parameters, dynamically at runtime, and following rules defined by yourself (routing).

• You can split messages – for example, send all messages with specific attributes to an additional system as well as the actual target system.

• By means of suitable adapters, you can convert messages from other formats into the XML message format of the Exchange Infrastructure and vice versa. For example, you

Page 46: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 41

can convert RFC-based calls into XML-based messages and communicate with external systems.

4.7 Making Enhancements With a wide spectrum of customizing options in systems, SAP enables customers to adapt SAP business programs to their processes. However, it is not possible to satisfy all customers’ wishes for individual adjustment or enhancement of SAP solutions to meet specific needs. In these cases, programmers can enhance or change the SAP standard.

Until now, there were two different concepts for this:

• Modification – that is, changing SAP development objects with the Modification Assistant.

• Enhancements – that is, source code enhancements to customer exists and Business Add-Ins (BAdIs), which have been possible since Release 4.6.

The classic solutions had some disadvantages:

• Upgrading customer systems featuring a large amount of user-developments required a lot of time and effort.

• It was difficult to trace various developments to an original system back to this system.

The new enhancement concept of the Enhancement Framework has the following features:

• Modification-free enhancements of existing development objects on different levels – for example, in an industry solution, in the IT department of the customer, and finally in a customer’s company.

• Integration of all enhancement types in a uniform framework

• Better upgrade support

• Switching of enhancements with the Switch Framework (not possible externally with 7.0)

• Support for grouping enhancements and appropriate documentation for this

Detailed information is available under Enhancement Framework [Extern] and Switch Framework [Extern].

4.7.1 How Do Modification-Free Enhancements Work? The basic idea of the Enhancement Framework is to make modification-free enhancements of development objects such as programs, function modules, and global classes. The question that arises is how enhancements without modifications work.

You can perform modification-free enhancements at predefined positions in code. There you have anchor points or enhancement options, as they are called in the terminology. At these points you can insert your enhancements. You can do this without changing the compilation unit that you are enhancing. The inserted implementations are processed at the appropriate position in the compilation unit, but they are themselves not part of this unit. They cannot, for example, belong to another package. Let us take a look at the example of a source code enhancement in a report in order to illustrate this better. We are not looking at details of coding, but want to give you a first impression of the working method of this enhancement technology.

Page 47: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 42

Anchor point, at which you can plug in an enhancement

Enhancement, which is executed here but is itself not a physical part of the code it is plugged into

Anchor point, at which you can plug in an enhancement

Enhancement, which is executed here but is itself not a physical part of the code it is plugged into

You can – to a certain extent – compare this enhancement technology with a closet system where you can insert various elements at particular positions. Instead of drilling the wood in the side walls, you can insert various boards and other elements where the manufacturer has already inserted hooks or holders at important positions.

There are different types of holders or attachments at various positions. At each holder type, you can insert exactly one type of element: boards at small dowel positions, CD elements at wider dowel positions, and drawer elements at multiple dowels. It seems like the elements are an integral part of the entire closet but, in fact, they are attached to the closet parts through holders. The different enhancement technologies correspond to these different types of elements described above. These technologies become attached at different types of anchor points or enhancement options of the Repository objects.

Therefore, you cannot simply insert enhancements into Repository objects at any position you like without modifications, but only where there are so-called enhancement options in place. At these enhancement options, you can also attach only certain elements – so-called enhancement implementation elements.

A concept that standardizes and structures all previous enhancement possibilities cannot do without a certain amount of complexity. The structure it is based on, however, is extremely simple.

• On the one hand, you have hooks or, to put it correctly, enhancement options where you can insert enhancements. There you define enhancement options, which is why one can speak of the definition side.

• On the other hand, you have enhancement implementation elements that you can affix to these hooks or enhancement options.

The rest is simple detail: There are various types of hooks or enhancement options, and there are also various enhancement implementation elements. The enhancement options are grouped together to enhancement spots and these, in turn, to even larger units. The same applies to units on the implementation side. Between the different units of a side and between those of the implementation and definition side, you have assignments of different cardinality.

Page 48: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 43

4.7.2 Enhancement Framework Details Based on an Example

Let us now go into more detail and examine the difference between implicit and explicit enhancement options: Implicit enhancement options always exist in the case of Repository objects of the relevant type. Explicit enhancement options have to be planned by the developer and inserted explicitly at the relevant point in the code.

You will then learn some more details about the source code plug-in – that is, how to insert source code plug-ins and in which units or containers such plug-ins are embedded. The purpose of this is not to cover every last detail, but to enable you to familiarize yourself with the functioning of enhancements.

4.7.2.1 What Are Explicit and Implicit Enhancement Options? From a definition point of view, there are explicit and implicit enhancement options:

• The developer of the corresponding development object must insert the options of the one kind into the coding so that enhancements can be done there at a later time. These preconceived enhancement possibilities are called explicit enhancement options.

• You can perform enhancements on implicit enhancement options without the developer of the appropriate compilation unit having to do anything. Enhancement options are always available in programs, global classes, function modules, and includes.

As described above, you can insert different types of enhancements at different enhancement options. You will become familiar with these in the following sections:

Enhancement Technologies at Explicit Enhancement Points:

• Explicit enhancement options of the enhancement point type allow you to insert source code plug-ins. These are additional code lines that, if they exist, are executed there additionally. Explicit enhancement options of the type Enhancement Section behave in the same way – the only difference being that the source code plug-in replaces the section in the original code.

• Business Add-Ins (BAdIs) are “hangers” for object plug-ins. A BAdI definition comprises an interface with methods. BAdIs are enhanced by classes that implement the BAdI interface. If you instantiate a BAdI and then call its methods, you can, among other things, specify which method implementations are to be carried out on the basis of filter values. In other words, a BAdI method call is a dynamic method call with a specified interface, for which it is not determined until runtime which method implementations are to take place.

4.7.2.2 Explicit Enhancement Options • There are two types of explicit enhancement options: Source code enhancements with

source code plug-ins and BAdIs:

• Explicit enhancement options of the source code enhancement type allow you to insert source code plug-ins. These are lines of code that are executed if the source code enhancement option is inserted in the code with the Enhancement Point command. Source code enhancement options with the Enhancement Section command behave the same, except that the source code plug-in replaces the section in the original code. Therefore, you are not only able to enhance the original code, but can also flag specific code sections (as enhancement sections) so that other developers can replace these sections with other code without making modifications.

Page 49: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 44

• Business Add-Ins (BAdIs) are “hangers” for object plug-ins. A BAdI definition comprises an interface with methods. BAdIs are enhanced by classes that implement the BAdI interface. If you instantiate a BAdI and then call its methods, you can, among other things, specify which method implementations are to be carried out on the basis of filter values. In other words, a BAdI method call is a dynamic method call with a specified interface, for which it is not determined until runtime which method implementations are to take place.

In the case of source code enhancements, the definition and call coincide. You define BAdIs once in the BAdI Builder and can then call them at different points in the various compilation units.

4.7.2.3 Implicit Enhancement Options Implicit enhancement options are fixed points in compilation units – that is, points that remain intact even if the code is changed. This is important for the following reason: If the location of an enhancement is moved, you have to check manually after an upgrade whether the enhancement is still at the correct point and replace it if necessary. The following are implicit enhancement options at which enhancements can always be inserted:

• You can always insert source code plug-ins before the first and the after the last line of includes, methods, reports, and function modules.

• You can always add further optional parameters to function modules.

• For global classes, there are different permanent, implicit options for enhancements: You can insert additional attributes or methods, and you can add optional parameters to existing methods.

4.7.2.4 Source Code Plug-Ins in Detail Enhancement options and enhancement implementation elements of explicit enhancement technologies are organized into larger units, which are assigned to one another in different cardinalities. The units are similar for all explicit enhancement technologies, but the cardinalities are different. Therefore, it would be useful to demonstrate the organization for explicit, that is planned enhancements of the source code using source code plug-ins to give you an impression of the structure.

The enhancement possibilities of the source code result from the insertion of an enhancement option. An enhancement option is an anchor point at which you can insert one or more (simple) enhancement implementations. When you insert an enhancement implementation at an enhancement option, a source code plug-in is created. At an enhancement option of the type Enhancement Point the enhancement implementation enhances the source code, while at an Enhancement Section exactly one implementation replaces the code in this section.

The following example shows how a source code plug-in is actually inserted into the code. The added enhancements are shown in the Editor at the points where they were inserted. However, they do not belong to the package of this source code unit, but instead to the package of the enhancement implementation that they are assigned to.

Page 50: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 45

SAP AG 2005, Title of Presentation / Speaker Name / 29

Source Code Plug in Technology

PROGRAM p1.

WRITE ‘Hello World’.

ENHANCEMENT-POINT ep1 SPOTS s1.

..

..

..

ENHANCEMENT-SECTION ep2 SPOTS s1.WRITE ’Original’.

END-ENHANCEMENT-SECTION.

PROGRAM p1.

WRITE ‘Hello World’.

ENHANCEMENT-POINT ep1 SPOTS s1.

..

..

..

ENHANCEMENT-SECTION ep2 SPOTS s1.WRITE ’Original’.

END-ENHANCEMENT-SECTION.

ENHANCEMENT 1.WRITE ’Hello Paris’.

ENDENHANCEMENT.

ENHANCEMENT 1.WRITE ’Hello Paris’.

ENDENHANCEMENT.

ENHANCEMENT 2.WRITE ’Hello London’.

ENDENHANCEMENT.

ENHANCEMENT 2.WRITE ’Hello London’.

ENDENHANCEMENT.

ENHANCEMENT 3.WRITE ’Enhanced’.

ENDENHANCEMENT.

ENHANCEMENT 3.WRITE ’Enhanced’.

ENDENHANCEMENT.

4.7.2.5 In Which Structure Are Source Code Plug-Ins Embedded? The units on the definition side – that is, the enhancement points – and the source code plug-ins are grouped into larger units in the cardinality 1:n. As you will see later, this assignment of enhancement points and source code plug-ins to larger containers reflects aspects relating to organization as well as content and supports a structured documentation befitting these aspects.

Let us first take a closer look at the structure, in which the enhancement points and their counterparts are embedded: An enhancement point belongs to precisely one enhancement spot, which can contain several enhancement points (1:n). Several different (simple) enhancement implementations can be assigned to an enhancement point and an enhancement implementation can be assigned to multiple enhancement points (m:n). As described above, assigning an enhancement point to an enhancement implementation creates a source code plug-in.

In the case of source code plug-ins at explicit enhancement points, the compilation unit is the connecting element: All units belong physically (definition side: enhancement points and enhancement spots) or logically (implementation side: enhancement implementations and source code plug-ins) to exactly one compilation unit, a report for example. In other words, an enhancement spot containing points of a report A cannot also contain points of another report B. The same applies to the implementation side.

Page 51: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 46

SAP AG 2005, Title of Presentation / Speaker Name / 33

Physical Part of Compilation Unit

Enhancement Spots & Implementations

SpotA

Point A

Section B

Point C

(Simple) EnhancementImplementation 1

(Simple) EnhancementImplementation 2

Point EPoint F

Spot Hugo

Spot Flights

(Simple) EnhancementImplementation 3

Compilation Unit

Assigned to Compilation Unit

Point D

The containers on the right – that is, the definition side – provide a clear overview according to semantic criteria. Here you can find information about which program sections can be enhanced to which business aspects. Developers of this first view can group different enhancement points into (simple) enhancement spots according to semantic criteria. For example, an enhancement spot can contain all enhancement points for customer address management, while another enhancements spot can contain all enhancement points for vendor address management, and the composite enhancement spot comprises all spots for enhancing the address management. If you, as a developer in an industry solution or for a customer, want to enhance the relevant programs and incorporate an additional search for customer and vendor addresses, you can look in the documentation for the composite enhancement spots and that for the simple enhancement spots and find the enhancement possibilities that semantically meet your requirements; you can then navigate to the relevant point(s) in the source code. Without this grouping of enhancement options into simple and composite spots, you would have to search the entire code for a suitable enhancement point.

The assignment of source code plug-ins and enhancement implementation elements to enhancement implementations and composite enhancement implementations supports the work organization of developers of enhancements. This assignment also defines how the implementations can be activated. Entire packages are switched, and the package assignment of the source code plug-ins or enhancement implementation elements is determined by the enhancement implementation to which they belong. This means, source code plug-ins that are to be switched separately must belong to different enhancement implementations. However, the granularity of this assignment will generally be too coarse. You will not pack all source code plug-ins that are to be switched together into one enhancement implementation, but instead make finer divisions according to projects and business aspects.

4.7.3 New BAdIs If you are planning new enhancements, BAdIs are the most important explicit enhancement technology for you. In the context of the SAP Enhancement Frameworks, BAdIs are specially designed object plug-ins. With BAdIs you can create specified enhancement options via an object-oriented interface and implement these options in the same or other systems at a later

Page 52: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 47

stage. BAdI implementation methods are called using a BAdI handle, which functions like an object reference syntactically but is technically implemented somewhat differently. If one or more filters are defined for the BAdI, you can, when calling the BAdI, select the BAdI implementations that meet specific filter conditions by passing these as parameters.

Unlike source code enhancements, in which user-defined code is inserted, BAdIs enable enhancements for which the developer of the code unit to be enhanced defines an enhancement option, but also specifies the interface for this enhancement. Developers thus have more control over enhancements. For this reason, BAdIs are a better prestructured enhancement option.

4.7.3.1 Features of New BAdIs The definition and implementation of BAdIs are completely unaffected by changes to the source code of the compilation units in which BAdI methods are called: You create BAdI definitions in the package of the relevant enhancement spot, which belongs to a separate package. A BAdI implementation’s package assignment is determined by the enhancement implementation to which this implementation is assigned. As a programmer, you define and implement BAdIs using the corresponding tools, which can also be called in the Object Navigator (SE80). The independence of BAdI definitions and implementations of source code units, at which BAdIs are called, is an advantage of BAdIs over source code enhancements, whose implementation – that is, the relevant source code plug-in – coincides with the implementation call and resides in the corresponding source code unit. If this unit is changed, the implementation of a source code plug-in could be lost, something that cannot happen with BAdIs for the stated reasons.

BAdIs also allow you to easily add multiple levels of enhancements, and you can do so without modifications since the levels are in different packages than the call position and the definition of the BAdI. Core developers can thus create a BAdI with a default class. A default implementation is added to the application and customers can include individual BAdI implementations. The following prioritization applies at runtime:

If no active BAdI implementation(s) exist(s) corresponding to the filter conditions, the system uses the relevant default implementation(s). If no corresponding default implementation(s) exist either, an implementation of the default class is used.

Depending on the type of the definition, there are BAdIs that must have one active implementation and others for which no or multiple active implementations are possible. Single-use BAdIs have completely different semantics to their non-single-use counterparts:

• Calling a method of a single-use BAdI (using CALL BADI) corresponds to a method call. Exactly one implementation must exist. The method of the implementation of this instance is then called. If there are no or multiple active implementations, different exceptions are raised in each case. One example are all method calls that deliver a return value. If you call such a method, you require a result. In these cases, you use single-use BAdIs.

• Calling a method of a non-single-use BAdI corresponds to an event. No or multiple implementations can be subscribed, so to speak, to this event. How many implementations this is, if any, is irrelevant for the logic of the program flow at the position where the event is triggered or the BAdI method is called. Semantically, you use non-single-use BAdIs where additional things can but must not occur. An example of this: You want to store specific results in other destinations, such as an XML file, a database table of an external database, or a serial file.

Page 53: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 48

4.7.3.2 BAdIs - Typical Example Let us use an example to clarify how to work with BAdIs.

You want to carry out country-specific validity checks upon completion of an order in the core. The interface of these validity tests is specified by the interface if_check_validity.

The current country is, as always, in the field sy-langu of the type lang. To be able to work with a method of a BAdI interface, you must first get an object that implements the interface if_check_validity (depending on the current country). In the second step, you can call the corresponding methods of this object (in this case, a BAdI with exactly on active implementation is semantically most useful) and the result of the validity tests is used in the core code. In this process, the core specifies the interface if_check_validity and its contract, while the subsequent systems provide the implementations.

You obtain a handle for a BAdI instance using the command GET BADI and call the interface methods using CALL BADI. If the BAdI definition created in the core is called badi_check_validity, check_validity(data) is the method that verifies the order data, and the country filter has the name language, the enhancement point is as follows: DATA bd TYPE REF TO badi_check_validity.

GET BADI bd FILTERS language = sy-langu.

CALL BADI bd->check_validity exporting data = data.

This code fragment shows that a BAdI is represented by a variable of the type REF TO badi_check_validity; BAdI names are thus in the same namespace as ABAP data types. Objects of this type are known as BAdI handles.

The GET BADI command then searches the Repository for currently active implementations and selects the one defined for the filter value sy-langu. It is instantiated and “appended” to the BAdI handle bd, which has also just been created. In the subsequent CALL BADI, the method call is passed on to the object instance of the BAdI implementation appended to the BAdI handle bd.

4.7.4 The Switch Framework With the Switch Framework, you can control the visibility of Repository objects. Among other things, this enables you to have all SAP industry solutions in one system and only activate the desired solutions.

The following describes how this is made possible and what use it is to you the developer. You will learn which elements can be switched and how. In other words, the following sections will familiarize you with the structure of the Switch Framework and its basic elements.

The fact that the enhancement implementations of the Enhancement Framework can be switched is an important aspect of the Switch Framework. Therefore, the Enhancement Framework and the Switch Framework are closely coordinated and complement one another in their functions.

Page 54: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 49

4.7.4.1 Motivation Let us imagine you want to add two different add-ons to a basic component and these add-ons enhance the same sections of the basic component and partially change them incompatibly. Previously, you would have required three systems for this – one for the unchanged basic component and one each for the basic component with the enhancements/changes of the relevant add-on – which entails a large amount of extra work and effort for corrections, maintenance, and upgrades. After all, you would be supplying three systems instead of one.

It would be significantly easier if you could keep the basic component, the basic component and add-on 1, and the basic component and add-on 2 separately but in a single system and then simply specify which of the three components you want to work with. Precisely this is possible with the Switch Framework, and you can drastically reduce the amount of effort required for the development and maintenance of the different add-ons.

The Switch Framework enables you to enhance or change a component, retain the original component as well as the enhancements/changes in the same system, and then decide whether to work only with the original component, or with the original component and one of the then activated enhancement components.

4.7.4.2 Basic Concepts of the Switch Framework The fundamental idea behind good solutions to problems is usually quite simple, and the Switch Framework is no exception, with its basic idea following quite simple logic: Previously, the Repository objects of a system were active in every client. With the Switch Framework you can use switches to control which Repository objects are active at runtime. Deactivated Repository objects are not compiled. At runtime, it is as if they did not even exist.

In our example, this means: The Repository objects of the basic component, which are changed in the add-ons, have to be switchable, just like all other parts of the code that are also included in the add-ons, be it additional code or replacement code for the basic component. If it is now possible to switch on either the unchanged basic component or one version each changed by the relevant add-on, you will have exactly what you need: You can develop and maintain the basic component and two different incompatible add-ons in one system. You can set the switches so that only the code of the desired version (basic component without add-on, basic component with add-on 1, or basic component with add-on 2) is compiled and thus available.

With the Switch Framework all SAP industry solutions can be lead back o one system, where they can be developed and maintained. And this is exactly what SAP does. This is a very real example of the usefulness of this framework. All industry solutions are delivered in one system in an inactive state. The customer then switches on one industry solution. Since the inactive Repository objects are not compiled, the performance of the individual industry solutions at runtime is the same as if the switched off Repository objects did not even exist. Therefore, the load is not increased.

4.7.4.3 What Objects Can You Switch and How? For you as a developer, it is very important to know which objects you can switch using the Switch Framework and how this switching works. This is what the following sections will

Page 55: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 50

discuss. You find out there how you can take precautions for conflict cases using the Switch Framework. A conflict situation is a situation where the switch is set such that two or several objects would be switched on that should not be switch simultaneously. To prevent this from happening, you have the so-called conflict switch.

4.7.4.3.1 Switchable Objects Switchable objects are split into two groups.

The following can be switched via their package assignment:

• Appends; SI and CI includes for Dictionary structures

• Fixed value appends for domains

• Secondary indexes

• Append search helps

• Enhancement implementations (including those containing BAdI implementations)

• Business Configuration Sets (BC Sets)

When a package is switched off, all switchable elements it contains are also switched off. Reports cannot be switched. However, a report belonging to a switchable package is not generated automatically after import. The reason for this is that the report could use switched off objects, which would lead to syntax errors during generation. When such a report is called, it is generated however. Whether a package is switched on or off has no effect on any other elements of the package.

The following are switched directly:

• Screen elements and PBO/PAI modules in the screen

• Menu entries

• IMG nodes

• Fields in maintenance views and views in Customizing view clusters

Transactions cannot be switched but you can switch the relevant transaction calls in the menu so that the transaction can no longer be called via the menu.

4.7.4.3.2 Switching Switches are assigned to switchable objects – that is, packages and directly switchable elements. Switches belong to business functions with the cardinality n:m.

A business function is a self-contained function with switches for objects of the relevant functionality. When you activate a business function, all corresponding switches are switched on.

Business functions belong to business function sets with the cardinality n:m. A business function set forms a unit covering the functionality of an industry solution. All business functions of a business function set are compatible with one another. On an ABAP-based SAP system, you can switch on no more than one business function set.

Page 56: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 51

Business Function Set

Business Function

Switch

n:m

n:m

4.7.4.3.3 Conflict Switches Some objects must not be switched on together. A typical example of this is the single-use BAdI: It is specified in its definition that is must have exactly one active BAdI implementation. Therefore, the corresponding switches cannot be switched so that several BAdI implementations compatible with the filter conditions are activated simultaneously when such a single-use BAdI is called.

Described more abstractly, a conflict arises if several enhancement implementation elements are switched on at an enhancement option when only one element should be.

For such cases, there are enhancement implementations that are assigned to a conflict switch. Any switch settings that could result in a conflict when combined must be assigned to a conflict switch, and an enhancement implementation that solves the conflict semantically must be assigned to the conflict switch.

SAP AG 2005, Switch Framework 42

Conflict resolution

The switched on conflict resolution enhancementimplementation resolves the conflict

Conflict ResolutionSwitch

„Normal“Switch 1

„Normal“Switch 2

Implementation 1

Implementation 2

Conflict Resolution Implementation

ON

ON

ON

Page 57: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 52

5 Ensuring Quality Unit testing is now widely used and accepted test philosophy, which significantly aids the programming of error-free software. The central idea is that regular testing of smaller program units, carried out by developers, should be an integral part of the development phase.

ABAP Unit, the tool for unit testing in ABAP, is integrated in the programming language and the development environment of the ABAP Workbench, which you will already be familiar with. With this tool, a whole range of unit tests with predefined test settings can be executed again and again at the touch of a button; the result display shows you at a glance which tests did not return the desired result and why. ABAP Unit thus makes unit testing so simple that testing your programs will be a lot more enjoyable.

Detailed information is available under ABAP - Analysis Tools [Extern].

5.1 ABAP Unit Tests

Structure of Unit Tests An ABAP Unit test unit (TU) can be a class, function pool, executable program, or module pool. You can call ABAP Unit for testing individual TUs from the Class Builder (SE24), Function Builder (SE37), ABAP Editor (SE38), and SE80. Mass tests can be carried out from the Code Inspector.

You organize your tests into classes and then into test methods, which are all part of the TU. The system checks small units within the TU, hence the name ABAP Unit. The aim of a test method is to check whether a unit returns the desired result. For this purpose, there are methods of the service class CL_AUNIT_ASSERT that execute comparisons between target and actual values calculated by a unit. The results of all unit tests of a TU are then shown in the ABAP Unit result display.

Example Let us look at an example to help clarify this. Our minimalist TU is a percentage calculator that delegates this task to a subroutine: REPORT Percentages.

PARAMETERS: price TYPE p.

PERFORM minus_ten_percent CHANGING price.

WRITE price.

FORM minus_ten_percent CHANGING fprice TYPE p.

price = fprice * '0.9'.

ENDFORM. "Minus_ten_percent

We add a test class to the report, which tests whether the subroutine correctly calculates the percentage for a specific value.

Page 58: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 53

CLASS test DEFINITION FOR TESTING. "#AU Risk_Level Harmless "#AU Duration Short

PRIVATE SECTION.

METHODS test_minus_ten_percent FOR TESTING.

ENDCLASS.

CLASS test IMPLEMENTATION.

METHOD test_minus_ten_percent.

DATA: testprice type p value 200.

PERFORM minus_ten_percent CHANGING testprice.

cl_aunit_assert=>assert_equals( act = testprice exp = 180

msg = 'ninety percent not calculated correctly').

ENDMETHOD.

ENDCLASS.

The test class and the test method TEST_MINUS_TEN_PERCENT are recognized by the tool through the addition FOR TESTING. The additions "#AU RISK_LEVEL HARMLESS and "#AU DURATION SHORT are not optional comments but annotations containing required technical information. With RISK_LEVEL you specify to what extent, if at all, executing the test endangers critical data. The time is specified so that any tests in endless loops are automatically cancelled due to a timeout. In the transaction SAUNIT_CLIENT_SETUP, you can make settings for an entire system with regard to the RISKLEVEL of tests and the times assigned to the individual attributes that specify the permitted duration (DURATION: SHORT, MEDIUM, and LONG). For example, in some development systems you will want to prohibit tests that change important data. If the test is cancelled for any reason, it is possible that some data may be left with invalid values or in an inconsistent state. Therefore, you will set the permitted RISKLEVEL suitably low in such systems.

Service of the Class CL_AUNIT_ASSERT As parameters, the service method CL_AUNIT_ASSERT=>ASSERT_EQUALS requires a target value and an actual value, which is the result of the tested calculation; it then compares the two values. The MESSAGE parameter should contain a text that explains what went wrong during the test. You can also pass a parameter with the service method CL_AUNIT_ASSERT=>ASSERT_EQUALS that specifies the severity of the error, as well as a parameter stating how to proceed if the test fails: Should the test method simply continue, or should the current test method, the entire test class, or all tests of the TU be canceled?

In addition to this method, the class CL_AUNIT_ASSERT also provides other methods, which execute different checks and pass the results to the framework. Most importantly, you should note that you can use the parameters of the methods of the service class CL_AUNIT_ASSERT to control the flow of the whole unit test and include information in the test methods that will later provide you with important details about any errors in the result display.

ABAP Unit Result Display On the left side of the result display, all the tests of your TU are grouped into a task. In our case, this is only one test class with a single method:

Page 59: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 54

Via the name of the method, you can see what parts of the test method caused errors during the test:

The message you passed with the service method is displayed at the top. Below that, you can which values diverge and can navigate to the class via the stack line.

In our example, a closer examination of the code reveals that the input parameter of the report was confused with the change parameter of the subroutine.

5.2 Effective Testing with ABAP Unit

Complete Test Coverage At first glance, the test in the previous case appears to be so simple that it would have been quite easy to establish why the program is not functioning correctly without the aid of a unit test. In actual fact, ABAP Unit is also the means for discovering errors in such simple cases.

The strengths of ABAP Unit are demonstrated even better when used in conjunction with large programs. Imagine a report SAMPLE_REP which calls 10 methods A-K of the local class LCL_X sequentially. A change request from a customer requires a different return value for the method LCL_X->A and, after adjusting the called service method LCL_SERV->SERVICE_M, the method LCL_P->A returns a result that satisfies the customer’s wishes. Now let us assume that changing the service method LCL_SERV->SERVICE_M has a side effect resulting in the method LCL_X->K running incorrectly: Method LCL_X->K now accesses the changed service method, but requires it in its original, unedited form, which no longer exists of course.

Page 60: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 55

Meth C

Meth B

Meth D

Meth K

Meth E

Meth F

Meth G

Meth I

Meth H

Meth A

ClassLCL_X

Report SAMPLE_REP

Class LCL_TEST FOR TESTING

Test_Meth TA

Test_Meth TB

Test_Meth TC

Test_Meth TD

Test_Meth TE

Test_Meth TF

Test_Meth TG

Test_Meth TH

Test_Meth TI

Test_Meth TK

Test_Meth TM

LCL_P->A( )…LCL_P->B( )…LCL_P->C( )…LCL_P->D( )…LCL_P->E( )…LCL_P->F( )…LCL_P->G( )…LCL_P->H( )…LCL_P->I( )…LCL_P->K( )…

Service classLCL_SERV

Service_M

Tests

If you have covered all the methods of your program with ABAP Unit tests, you will discover this side effect at the touch of a button – that is, as soon as you run the unit tests for your TU, in this case the report SAMPLE_REP. This also underlines one of the central ideas of unit tests, the complete test coverage of TUs.

Providing Good Test Data – Methods SETUP and TEARDOWN A further important condition for the effective testing of complex programs is good test data. You should be systematic and continue to work with the same initial test data. This means, you should also be able to set up test data in your unit test. To avoid your tests affecting one another, different tests that all work with the same data should always be able to access this data in unaltered form. This is one aspect of the fact that unit tests should run isolated from each other.

The setup of test data and test objects is supported by ABAP Unit in the form of fixture methods. There is a SETUP method in a test class, into which you can relocate the data setup that is required before each test. If you require a specific internal table in its initial state for each test, you do not have to recreate it in every test method. You can relocate this into the SETUP method. There is also a corresponding TEARDOWN method for the SETUP method, with which you can release the resources again. To avoid the individual tests influencing one another (isolation requirement), the SETUP method is executed before and the TEARDOWN method after the execution of each test method.

Repeatedly setting up specific test resources can be very performance-intensive, and it is also unnecessary if this data is not changed by the test methods but only read. For this purpose, there is a CLASS_SETUP and a CLASS_TEARDOWN method.

Page 61: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 56

Start Internal Session for Test Class

Class-Construction of Test Class

Set-up Class Fixture

For Each Test Method

Tear Down Class Fixture

Create Test Instance

Set-up Instance Fixture

Run Test Method

Tear Down Instance Fixture

You have now encountered two fundamental ideas of unit tests: It is important to achieve complete test coverage and it is worth investing some effort in the quality of the test data. We have now reached a point where you can start to learn a little more about the general philosophy of unit tests.

5.3 The Philosophy of Unit Tests

Testing Isolated Functional Units The individual tested units should, if possible, be of smallest size and independent of one another. You should choose as units the smallest unit that supplies a result that can be checked. Ideally, the units should not access each other. However, this requirement is really an ideal situation, and not always practical. In any case, the tests that run one after the other should not work with data or objects that were already changed by another test.

Test small code units provides different advantages:

• In the case of an error, the problem can be easily localized if the unit is very small.

• Ideally, an error cannot influence other tests in a test due to the isolation requirement.

• Simple unit tests require less effort than complex test scenarios.

Testing During Development Unit tests are executed regularly during development. This has the consequence that test phases cannot easily be shortened or even discarded as in the classic case where testing occurs only after development.

Precise Specifications Through Testing Unit tests force you, the developer, to give precise definitions as to what a particular procedure should do and which return values it should supply. If you cannot think of any unit test for a particular procedure, this could be an indication that you should rethink the specification for this procedure.

Conversely, it is a good idea to firstly define unit tests for a procedure and then to implement the procedure. In any case, the implementation of unit tests will help you to specify your

Page 62: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 57

procedures more precisely and to find out whether the implementation actually matches the specification.

Better Modularization Through Testing If you attempt to split your test unit into units that you can test independently of one another, you will achieve a higher degree of modularization. While you are designing your unit tests, you will notice where coding is not sufficiently modularized and you will adapt it accordingly. In this way, your productive coding will be better.

Systematic Testing Unit tests are systematic. You ideally cover all parts of a test unit and the tests are always executed with the same test data. This has many advantages as compared with irregular tests that developers execute anyway: No test cases are lost, you can navigate without any difficulty to the problematic code lines after the test and do not have to search through lines of code – as is the case if you are working with traces.

Unit Tests as White Box Tests Unit tests are typical white box tests, which only the developer himself/herself can execute. The developer knows his or her coding so well that he or she can test the smallest functional units. The individual tests may appear trivial to you and may not appear worth the effort. Together, the unit tests provide you with the assurance – in the case of full test coverage and regular execution – that everything will still work after program changes if it was working beforehand.

Unit Tests Versus Debugging or Traces Unit tests are automated. In the Debugger, you have to enter your test manually all the time. Therefore, with unit tests – as compared with debugging – you always have the same test data at your disposal, without extra effort, and you do not waste additional time in making preparations for a test run. Not to mention that fact that it is not enticing in the Debugger to fill the variables required for the test over and over again with the same data.

Unit Tests Versus Integration Tests In comparison to integration tests, the unit for unit tests is very small, and unit tests occur very early on during development. Their role is thus made even more important: Integration tests can be focused on errors that occur through integration because the individual units are already tested before integration. Unit tests show up errors in an early phase of the life cycle of a component. In this way, you – as programmer – have considerably more time to correct them and it also saves others having to work with your incorrect code.

5.4 Unit Tests and Transports

ABAP Unit Tests as Part of the Production Code In ABAP Unit, test classes are part of the production code of the TU. This avoids problems arising from the test code being separate from the production code:

• Programs and tests must be kept synchronized.

Page 63: Using ABAP - ABAP and HANA ABAP.pdfUsing ABAP 1 1 Using ABAP ... object-oriented interfaces anyway. • Sharing Data: [Seite 20] With ABAP shared objects, you can aggregate data once

October 2005

Using ABAP 58

• You have to ensure that the test and program code are transported together.

• External test code only enables black box tests with an outside perspective of the tested program.

Since the test code is part of the production code, it is easy to keep the unit tests and the production code up to date if the latter is changed.

No Unit Test Code in the Production System Although the test code and the production code are transported through the system landscape, ABAP unit tests do not increase the load on the production system. By default, the test code is not compiled in the production system. Therefore, the test code can never be executed in the production system.

However, this has one important consequence for the creation of TUs with unit tests. The test code references the production code, but the reverse is not possible and leads to an error message when compiling: Program code must never reference test code. Whether or not there are dynamic accesses from the program code to the test code can only be checked at runtime. If there are, this causes a runtime error. Otherwise the production system would contain empty references in the production code after the test code has gone.

Unit tests and integration tests have one thing in common: Both test types require test data, the quality and coverage of which can decide whether or not a test is successful.

5.5 Advantages of ABAP Unit Tests With complete test coverage of the functional units of a test unit and regressive testing – that is, tests after any change to the TU – you significantly improve the quality of your software. With ABAP Unit, you can execute all tests in a TU at the touch of a button. Of course, the significance of any test also depends on the quality of the test data. You should consider your test data carefully and make sure that it covers all borderline cases. However, you should pay particular attention to testing the everyday cases, which make up some 90 per cent of regular operation. While this does not guarantee that your software will be completely free of errors, it will significantly reduce the number of errors and messages you receive. Furthermore, integration tests focus more on errors resulting from the interaction between individual components and you will have fewer errors caused by deficiencies of individual components.