abap advanced

126
1 SAP TechEd ‘07 CD350 Advanced ABAP Programming

Upload: sathish-bollabattula

Post on 01-Jul-2015

309 views

Category:

Education


21 download

DESCRIPTION

vvvv

TRANSCRIPT

Page 1: Abap advanced

1

SAP TechEd ‘07

CD350AdvancedABAP Programming

Page 2: Abap advanced

2

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Disclaimer

This presentation outlines our general product direction and should not be relied on in making a purchase decision. This presentation is not subject to your license agreement or any other agreement with SAP. SAP has no obligation to pursue any course of business outlined in this presentation or to develop or release any functionality mentioned in this presentation. This presentation and SAP's strategy and possible future developments are subject to change and may be changed by SAP at any time for any reason without notice. This document is provided without a warranty of any kind, either express or implied, including but not limited to, the implied warranties of merchantability, fitness for a particular purpose, or non-infringement. SAP assumes no responsibility for errors or omissions in this document, except if such damages were caused by SAP intentionally or grossly negligent.

Page 3: Abap advanced

3

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Contributing Speakers

Frank BertelsmeierSenior Developer, SAP AG

Rolf HammerDevelopment Architect, SAP AG

Page 4: Abap advanced

4

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Learning Objectives

As a result of this workshop, you will be able to:Utilize design aspects how to write reusable services in ABAPMake use of the generic programming concepts in ABAP

– Generic types, field-symbols and data references– Dynamic statements– Run Time Type Services

Implement robust exception handling in your ABAP coding using– Class-based Exceptions– Resumable Exceptions

Page 5: Abap advanced

5

SAP TechEd ‘07

Exception Handling

Advanced Programming Guidelines

Generic Programming

Page 6: Abap advanced

6

SAP TechEd ‘07

How to Organize your Software?How to Accomplish Reuse?ABAP Programming Recommendations

Page 7: Abap advanced

7

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Software Architecture Principles

NW AS ABAP

Application Implementation

(One or several ABAP programs)

Software architecture

Architecture PrinciplesInformation hiding =Define modules as black boxes only showing relevant information

Defines software (like an ABAP application) to be decomposed and organized in moremanageable parts (= components / modules / services) and how these interact.Goal: Increase quality, comprehensibility,

reusability and maintainability.

Module decoupling and cohesion =Minimize grade of dependencies (e.g. exchanged data) and find logical and consistent grouping of functionality

Open-close principle =Consider openess for extensibility orchangeabilty

The most fundamental problem in software development is complexity. There is only one basic way of dealing with complexity: Divide and conquer.(Bjarne Stroustrup)

The only problems we can really solve in a satisfactory manner are those that finally admit a nicely factored solution.(Dijkstra, 1972)

Simon (1962): “The fact, then, that many complex systems have a nearly composable, hierarchic structure is a major facilitating factor enabling us to understand, to describe, and even to 'see' such systems".

Definition 2-4 (Encapsulation, IEEE 610.12-1990): A software development technique that consists of isolating a system function or a set of data and operations on those data within a module and providing precise specifications for the module.

...the best programs are designed in terms of loosely coupled functions that each does a simple task. (Kernighan, Plauger, 1974)

Page 8: Abap advanced

8

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Software-layer Architecture

NW AS ABAP

Layer architecture

Layer PrinciplesHierarchical organizationEach layer focuses on one subproblem(provides similar functionality)Each layer ideally uses only the layer below it and provides services for the layer above Communication between layers by stable interfaces (protocols)Implementations are replaceable

Assign the components of a software to different concerns or layers of abstraction(partioning) and reflect their interface interdependencies (behaviour).

Layer 1

Layer n

Layer 2

Page 9: Abap advanced

9

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Example for Software-layer Architecture

Organize your application logic according classic

Three-tiered architecture

NW AS ABAP Non-ABAP

UI Logic

Persistence

ServicesApplication

Presentation layer

Application layer(Business logic)

Persistence layer

Screens, controls,flow logic, commands etc.

Data repositories, transaction service

Page 10: Abap advanced

10

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Separation of Presentation, Business logic and Persistence

Separate presentation logic from application logic– Coding that manages screen flow or screen appearance (as well as event

handlers for screen and control events) is not to be mixed with screen-independent application or business coding

Is the basis for:– Programming of reusable services (Access to business logic using

different UIs or different automated clients)– Testing of business logic by using isolated unit tests

Is supported by the MVC (Model View Controller) approach– Web Dynpro ABAP: automatically based on MVC– BSP: offers MVC support– Classic Dynpro: no built-in MVC Support

Separate persistence logic from application logicIs the basis for:

– Using different data provider services (simulation of DB operations)– Controlled DB access, including additional services, e.g. caching,

locking, transaction managementIs supported by the persistence model in the ABAP “Object Services”

The basic rule for programming user interfaces is to separate presentation logic from application logic. Do not mix coding that manages screen flow or screen appearance (as well as event handlers for screen and control events) with screen-independent application or business coding. Only application logic that is independent from the presentation logic allows:

– Access to business logic using different UIs.

– Access to business logic using different automated clients (i.e., non-human users).

This so-called “separation of concerns” is a basic programming model for supporting stability and maintainability because it allows:

– Programming of reusable services

– Testing of business logic by using isolated unit tests

Page 11: Abap advanced

11

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

MVC for decoupling presentation and application logic

Request

Response

User Interaction Layer

Business Interaction Layer

Binding Layer

Visualizes the application data without caring how it was generated.

Generates the application data without caring how it will be displayed.

Binds the user and business interaction layers together. All intermediate processing is performed here.

Model View Controller (MVC)

Model

View

Controller

Model-View-Controller (MVC) design paradigm originally invented by the Norwegian software designer Trygve Reenskaug (pronounced “TRIG-vuhRAINS-cow”) whilst working at Xerox PARC in the late seventies. The first implementation of this design paradigm was with the release of the Smalltalk-80 programming language.

MVC was a revolutionary design paradigm because it was the first to describe software components in terms of:

– The functional responsibilities each should fulfil.

– The message protocols to which each component should respond.

Page 12: Abap advanced

12

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Separation of Presentation Logic – MVC for Classic Dynpro

Class Pool

GlobaleDaten

GlobaleDaten

GlobaleDaten

GlobaleDaten

Dynpro

ScreenLayout

GUI Status GUI Functions

DynproFields

GlobalData,Local

Classes

PBO

PBOModule

PAI

PAIModule

Function Group

FUNCTIONMODULES

CALL SCREEN …

GlobalClass lokale

Klassenlokale

KlassenLocal

Classes

View

Control

Model

Include no operational statements in dialog modules. Use dialog modules for screen handling only. You might even reduce the implementation of dialog modules to an absolute minimum by programming the screen handling in methods of additional local classes.

Write all coding necessary for classic dynpros in dedicated framework programs that are separated from the application programs. Since Dynpros are not supported in global classes, the ABAP program type that is most appropriate to encapsulate classic dynpros are function groups, since they can contain dynpros as components and they offer function modules as a defined public interface. For an example, see the appendix in “Not Yet Using ABAP Objects? Eight Reasons Why Every ABAP Programmer Should Give it a Second Look”(SAP Professional Journal, September/October 2004).

Classic dynpro fields require global data objects in the framework program (function group); reduce the number of necessary global variables in the function group to the absolute minimum. In order to fulfill the separation of presentation logic from application logic also on the level of data types and data objects, declare a dedicated structure in the ABAP Dictionary for each dynpro, representing the fields and semantic properties for that dynproinstead of using the structure definitions of data base tables directly. The only global variables declared in the function group should be the structures for the dynpros encapsulated by the function group.

Page 13: Abap advanced

13

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Decoupling and Law of Demeter (LoD)

Minimize coupling of components: Law of demeterEach component should only have limited knowledge about other

components - “Only talk to your immediate friends”

CLASS classDemeter DEFINITION. PUBLIC SECTION.

METHODS doSomethingIMPORTING paramA TYPE REF TO classA.

PRIVATE SECTION.METHODS helpMeth RETURNING VALUE(count) TYPE I.DATA attrB TYPE REF TO classB.

ENDCLASS.

CLASS classDemeter IMPLEMENTATION. METHOD doSomething.

DATA localC TYPE REF TO classC.paramA->notify( ).attrB->setActive( ).CREATE OBJECT localC.localC->setCounter( me->helpMeth( ) ).

ENDMETHOD.ENDCLASS.

Methods of instances passed

as parameter

Methods of instances passed

as parameter

Methods of attributes of own

class (association)

Methods of attributes of own

class (association)

Methods of ownclass

Methods of ownclass

Methods of locally created instancesMethods of locally created instances

Page 14: Abap advanced

14

SAP TechEd ‘07

How to Organize your Software?How to Accomplish Reuse?ABAP Programming Recommendations

Page 15: Abap advanced

15

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

What Means Reuse?

Don’t repeat, use parts and knowledge of existing softwareReuse increases efficiency in software development– Saves costs, reduces effort– Reduces bugs, improves qualitiy

Dangerous: Ad-hoc reuse (copy & paste, shared includes)Planning of reuse (Krueger, Software Reuse, ACM Survey, 1992)– Abstraction: Identify units of reusable knowledge– Classification: Employ reusable knowledge– Selection: Find the appropriate reusable knowledge– Specialization: Adapt it to your needs– Integration: Use it in your project

Examples of Reuse and their reuse aspect– Service, module (class): Code– Generic service: Planned variants of code– Design Patterns: Concept for design & construction– Framework: Design and code– Generator: Knowledge how to implement a specified task

Requires initialinvestment, butquickly paid off

Definition 2-2 (Abstraction, IEEE 610.12-1990): A view of an object that focuses on the information relevant to a particular purpose and ignores the remainder of the information.

Page 16: Abap advanced

16

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

How to Achieve Reuse?

Good modularization is basis for reuseIdentify modules: One self-contained concept / concern / aspectConsider architecture principles– Information hiding, decoupling, cohesion: Be secretive, terse, independent– Orthogonality: Be concise, but complete– Start specific, but be open for further generalizations

Avoid any kind of repetition (redundant data, duplicated code etc.)

Enhance such modules to reusable serviceswhich implements a well-defined functionalitywhich have an orthogonal, concise interfacewhich can be used independently of other componentswhich are open for useful extensionswhich are intuitive to use (naming, behaviour)which are reliable (module tests)

Page 17: Abap advanced

17

SAP TechEd ‘07

How to Organize your Software?How to Accomplish Reuse?ABAP Programming Recommendations

Page 18: Abap advanced

18

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Reusable Services in ABAP Objects

How to adapt these criteria in ABAP?Use ABAP Objects– OO modeling reflects the entities of the reality in a natural way– Entities (= instances) encapsulate data and behavior– Supports information hiding– Allows reuse of classes by specialization (inheritance + redefinition)– Offers different views on entities by using interfaces– Has built-in event handling for loose coupling of entities

ABAP Objects opens the door to advanced ABAP technologies– Runtime Type Services (RTTS)– Advanced Exception Handling– Shared objects

ABAP cleanup effective in ABAP Objects and Unicode-enabled programs

Page 19: Abap advanced

19

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

ABAP Programming Recommendations

Defensive programming: Start as restrictive as possible and ease the restrictions only if needed:– Restrict visibility: PRIVATE/PROTECTED vs. PUBLIC– Restrict instance creation (CREATE PRIVATE) and offer factory methods– Restrict inheritance and redefinition: FINAL– If you use public attributes: READ-ONLY

Also for internal modularization use local classes to provide helperimplementationPrefer instance methods rather than static ones (use singleton patterninstead)Use inhertiance only for „Is-a“ relations vs. delegates for „Has-a“relationsSeparate declarations from implementations– Use global declaration part (TOP-include) for class/interface definitions and

global data declarations only for classic dynpro– Implementations are to be placed separately (never in TOP-include)– Use additional includes to further organize one and only one ABAP program

Page 20: Abap advanced

20

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Development & Testing

Ensure quality and reliability by regularly testing your serviceCode Inspector– Don’t run into problems which can be detected by static code checks– Sophisticated code analysis for robustness, performance, security etc.

ABAP Unit– Introduce “Self-testing” to your component – use it after each modification– Functionality of the service is executed under well-defined test conditions, the

results are inspected by checking them against expected results and thus verified

– Always: Implemented behavior + contract + runtime test of contract– Integrate “Testability” of your service from the beginning (design of service)

System Analysis & Design

Testing

Requirements Analysis

Development Life Cycle

Implementation Testing Maintainance

But testing isubiquitous!

Page 21: Abap advanced

21

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Static Checks: Code Inspector

Code inspection from editor:The Code Inspector executes a default test set for a chosen program.

The default tests also contain the Extended Program Check (SLIN).

ABAP Editor

Code inspectortransactions

SCII for ad-hoc checks

SCI for regular and/or parallelized mass tests

The code inspector (Transaction SCI) is a mass test framework which is delivered with WEB AS 6.10.(for R/3 >=46C a transport is available, see note 543359)

You can define your own:– program set (which programs shall be checked?),

– Test set (which test shall be executed – you can even define your own checks)

From the ABAP editor you can access the code inspector with a default program set (the program which is currently in use of the ABAP editor) and a default test set. This global default test set has the name “default” and can be adapted to your requirements like any other test set.

The default test set contains the following tests:– Performance checks (e.g. tuning of select statements)

– Security checks (e.g. client depending INSERT/UPDATE….)

– Extended program check

Page 22: Abap advanced

22

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

ABAP Unit – Writing Tests

ABAP Unit tests are implemented as local ABAP Objectsclasses in the ABAP program that contains the testedcomponents.

1. Write a local class with the extension FOR TESTINGClass Builder: Utilities → Test Classes → Generate

2. Write at least one method in this class with no parameters and extension FOR TESTING.

3. Implement your test code inside the methods from step 2. Use methods of utility class CL_AUNIT_ASSERT for verification of the expected state of the modularization unit after calling it in the test method.

4. Use methods SETUP for initialization and TEARDOWN for cleanup of test fixture (called before and after each test)

5. Execute the unit testClass Builder: Class → Module TestABAP Editor: Program → Execute → Module Test

Have a look at the class cl_aunit_assert for the different kinds of methods to check and verify the expected behaviour of your modular units.

Consider inheriting from cl_aunit_assertFixtures serve to build up a context in which a test shall be executed.Fixtures are defined by a naming convention, i.e. the methods setup, teardown and class_setup and class_teardown, respectively.

Page 23: Abap advanced

23

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

ABAP Unit – Result Display

At the end of an ABAP Unit run, the results are displayed directly (if run from the ABAP Editor via ) or collected in the result of a Code Inspector run.

Page 24: Abap advanced

24

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

ABAP Editor – Code Completion

Code Completion provides easy access to services

Code CompletionSuggests context-sensitive continuations for current edit position

Lets the user insert the selected entry or a code template

Offers easy access to repositories like ABAP class library or DDic

Page 25: Abap advanced

25

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

ABAP Editor – Code Completion Invocation

Context-sensitive code completion (CTRL+SPACE)– Fields (variables, constants, field-symbols, parameters etc.)– Types and classes (local and global)– Components of classes, interfaces, structures– Formal parameters and exceptions of methods, functions and subroutines – Function modules– Subroutines– Keywords

Insertion of identifiers (RETURN, TAB, Doubleclick)

Insert pattern (SHIFT + RETURN, SHIFT + TAB, SHIFT + Doubleclick)– CALL METHOD

– CREATE OBJECT

– RAISE EVENT

– RAISE EXCEPTION TYPE

– CALL FUNCTION

– PERFORM

Detailed Quick-Info

Page 26: Abap advanced

26

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

ABAP Programming Guidelines – Summary

Writing modern ABAP means:Keep your coding structured and modularized — always use ABAP ObjectsKeep up the separation of concerns – model your applications strictly service-oriented, always disentangle the logics for presentation and applicationKeep your coding clean — don’t use language elements that are marked as obsolete, especially work only with Unicode enabled programsKeep your coding up-to-date — have an eye on the ABAP language news and apply new constructs in your coding as they become available (it might be worth the effort to rewrite one or the other of your outdated application programs)Keep up the quality - test all parts of your programs with the appropriate tools

Page 27: Abap advanced

27

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Exercise 1

Page 28: Abap advanced

28

SAP TechEd ‘07

Exception Handling

Advanced Programming Guidelines

Generic Programming

Page 29: Abap advanced

29

SAP TechEd ‘07

Basic Generic ConceptsDynamic StatementsDynamic Type Creation

Page 30: Abap advanced

30

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Basics of Generic Programming

Generic ProgrammingCoding is able to deal with more generally typed dataTechnical properties – usually given statically in your code – are passed dynamically, mostly as value of a variable, e.g.,– Name of database table– Component names for filtering or sorting– Select condition– Type of a structure / internal table

Generic ServicesUsage of service is widened to (planned) variantsIncreased reuse rangeAbstraction necessary: Extract the core purpose and supply remainder otherwiseExample: ALV

What is generic programming?Technical properties of your code which are usually given statically in the code are given dynamically, e.g. as parameters

– Name of a database table to select from

– Sorting order

– Select Condition

– Type of a structure

What is a generic service?Extend the usage of your service also to planned variants of it (within a certain usage range)

– Generic Types

– Dynamic statements

– Dynamic data creation

– Type creation at runtime

Example: Generic Database InspectorPrint contents of database table with user-supplied parameters

– Name of database table

– WHERE condition

Page 31: Abap advanced

31

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

SORTED TABLE

ANY TABLE

STANDARD TABLE

INDEX TABLE HASHED TABLE

C, N, X, PCLIKE, CSEQUENCE, XSEQUENCE

ANY, DATA

SIMPLE, NUMERIC

Fully generic (i.e. untyped)

Partially generic

Generic length

Generic table kind and key

Generic Types

A generic type unites a set of types and – like a non-generic type –defines a set of operations be used on values of that type.Example: On values of type NUMERIC arithmetic operators are defined.

Page 32: Abap advanced

32

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

FIELD-SYMBOLS:<fs_any> TYPE any,<fs_c> TYPE c. "of any length

Generic type specification used forParameters

Field symbols

Data references

METHOD foo_1 IMPORTING p1 TYPE any....

ENDMETHOD.

METHOD foo_2 IMPORTING p1 TYPE numeric.... p1 = p1 * 2.

ENDMETHOD.

Generic Types

DATA:dref_any TYPE REF TO DATA,dref_con TYPE REF TO structtype. "concrete type

Page 33: Abap advanced

33

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

DATA: text(20) TYPE c VALUE 'Hello world'.

FIELD-SYMBOLS:<fs> TYPE any.

ASSIGN text TO <fs>.WRITE / <fs>.

ASSIGN text TO <fs> CASTING [TYPE … | LIKE …]WRITE / <fs>.

Field symbolsAliases for existing data fields (or parts of them)Assigned at run timeNo copying of data, just referring to same memorySimilar to parameters which are passed “Call-by-reference”Casting possible to obtain a specified technical view on the data

Field Symbols

Page 34: Abap advanced

34

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Casting Field Symbols

TYPES: MY_TYPE(9) TYPE C.

DATA: SmallField(5) TYPE C,LargeField(10) TYPE C VALUE '1234567890',TypeName(7) TYPE C VALUE 'MY_TYPE',

SomeType TYPE REF TO cl_abap_typedescr.

FIELD-SYMBOLS: <fa> TYPE any,<fs> TYPE my_type.

ASSIGN LargeField TO <fs> CASTING. ASSIGN LargeField TO <fa> CASTING TYPE MY_TYPE.

ASSIGN LargeField TO <fa> CASTING TYPE N.

ASSIGN LargeField TO <fa> CASTING TYPE (TypeName).SomeType = cl_abap_typedescr=>describe_by_name( 'MY_TYPE‘ ).ASSIGN LargeField TO <fa> CASTING TYPE HANDLE SomeType.

ASSIGN LargeField TO <fa> CASTING LIKE SmallField.

ASSIGN LargeField TO <fa> CASTING LIKE <fa>.

Casting to …

... statically completelyspecified type

... generic type

…dynamic field type

... static fieldtype

... dynamicallyspecified type

Page 35: Abap advanced

35

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Data References

Data references are pointers to data objectsUsing non-generic reference types

Using fully-generic reference type

Reference types can also be used in classes, structure types etc.

Typical uses for data referencesSave pointers to previously processed dataBuild generic containers for arbitrary data objectsCreate advanced data structures (like trees)

DATA iref TYPE REF TO typename.

DATA dref TYPE REF TO DATA.

Page 36: Abap advanced

36

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Usage of Data References

Assigning a data reference variable

Access always requires dereferencing (->*, ->)

Access to typed reference

Access to untyped reference

GET REFERENCE OF DataObject INTO drefCREATE DATA dref TYPE | LIKE ...

FIELD-SYMBOLS: <fs> TYPE any,<fc> TYPE any.

ASSIGN dref->* TO <fs>. "access complete data object ...ASSIGN COMPONENT 'COMP' OF STRUCTURE <fs> to <fc>."... then access component (in case of structured data)

X = dref->*. "access the complete data objectY = dref->comp. "access component of a structure

Page 37: Abap advanced

37

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Dynamic Creation of Data Objects

TYPES: BEGIN OF struc,a TYPE i,b TYPE c LENGTH 8,

END OF STRUC.

DATA: dref TYPE REF TO DATA,tname TYPE string,str TYPE struc,int TYPE i.

FIELD-SYMBOLS: <int> TYPE i,<str> TYPE struc,<f> TYPE any.

dref

CREATE DATA dref TYPE struc.

dref

ASSIGN dref->* TO <str>.

<str>

36 ABC

<str>-a = 36. <str>-b = 'ABC'.

dref

CREATE DATA dref LIKE int.ASSIGN dref->* TO <int>.

<int>

5

<int> = 5.

dref

tname = 'SFLIGHT'.CREATE DATA dref TYPE (tname).ASSIGN dref->* TO <f>.

<f>

SELECT SINGLE * FROM (tname) INTO <f>.

000 AA 0017

Page 38: Abap advanced

38

SAP TechEd ‘07

Basic Generic ConceptsDynamic StatementsDynamic Type Creation

Page 39: Abap advanced

39

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Dynamic Statement

Statements usually use arguments that refer to names of entitiesdefined in the ABAP code or in a repository like the DDic.

Static statement: STATEMENT … argument …

Some ABAP statements can be supplied with coding for certainarguments dynamically.

Dynamic statement: STATEMENT … (field) …

To substitute the dynamic part (field) the content of field is evaluated at runtime.

dbname = 'SFLIGHTS'.SELECT * FROM (dbname) INTO wa WHERE CARRID = 'LH'.compname = 'COMP'.SORT itab BY (compname).

SELECT * FROM SFLIGHTS INTO wa WHERE CARRID = 'LH'.SORT itab BY comp.

Page 40: Abap advanced

40

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Dynamic Statement Parts

Entities that statements may specify dynamically includeFieldsTypesStructure componentsForms, methods, functions, and programs, including parametersStatement subclauses

RestrictionsValue of dynamic part must be supplied in upper caseNo static type checks for dynamic statementsRuntime error occurs if value of dynamic part is invalid

Page 41: Abap advanced

41

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Refer dynamically to a field or a database tableASSIGN (field) TO …

SELECT … FROM (dbtab) …

DELETE … FROM (dbtab) …

MODIFY (dbtab) …

UPDATE (dbtab) …

WRITE … TO (field)

WRITE (field) TO …

Dynamic Field Specification

CONSTANTS: a TYPE i VALUE 1,b TYPE i VALUE 2.

DATA: name(5) TYPE c.

FIELD-SYMBOLS: <i> TYPE i.

* Dynamic ASSIGN to aname = 'A'.ASSIGN (name) TO <i>.WRITE: <i>. "=1

* Dynamic ASSIGN to bname = 'B'.ASSIGN (name) TO <i>.WRITE: <i>. "=2

Page 42: Abap advanced

42

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Dynamic Type Specification

Refer dynamically to local types or data dictionary typesASSIGN ... CASTING TYPE (type)

CREATE DATA ... TYPE (type) ...

CREATE DATA ... TYPE TABLE OF (type) ...

DATA dref TYPE REF TO data.FIELD-SYMBOLS <dobj> TYPE any.

* create data object of type* given by tnameFORM create

USING dref TYPE REF TO datatname TYPE string.

CREATE DATA dref TYPE (tname).ENDFORM.

TYPES: BEGIN OF struc,a TYPE i,b TYPE p,

END OF struc.PERFORM create

USING dref 'STRUC'.ASSIGN dref->* to <dobj>.

PERFORM createUSING dref 'SFLIGHT'.

ASSIGN dref->* to <dobj>.

Page 43: Abap advanced

43

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Refer dynamically to structure componentsSORT ... BY (comp1) ... (compn)

READ TABLE ... WITH KEY (k1) = v1 ... (kn) = vnDELETE ... COMPARING (comp1) ... (compn)

MODIFY ... TRANSPORTING (comp1) ... (compn)

ASSIGN COMPONENT (comp) OF STRUCTURE ...

Statements processing internal tables ignore empty parts

Dynamic Component Specification

DATA: itab TYPE TABLE OF some_type,key1 TYPE string, key2 TYPE string.

SORT itab BY (key1) (key2).READ TABLE itab INTO wa

WITH KEY (key1) = val1 (key2) = val2BINARY SEARCH.

Page 44: Abap advanced

44

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Dynamic Clause Specification

Include statement clauses dynamically with internal tablesSELECT (fieldlist) ...

SELECT ... GROUP BY (fieldlist)

SELECT ... WHERE (condlist)

TYPES: cond TYPE c LENGTH 72.DATA: wa TYPE spfli,

condtab TYPE TABLE OF cond.

* fill condition tableAPPEND 'CARRID = ''LH'' AND' TO condtab.APPEND 'CITYTO = ''NEW YORK''' TO condtab.

* database fetch with dynamic WHERE conditionSELECT * FROM spfli INTO wa WHERE (condtab).WRITE: / wa-carrid, wa-connid, wa-cityfrom.

ENDSELECT.

Page 45: Abap advanced

45

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Exercise 2

Page 46: Abap advanced

46

SAP TechEd ‘07

Basic Generic ConceptsDynamic StatementsDynamic Type Creation

Page 47: Abap advanced

47

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Dynamic Type Creation

Functionality

Type identification and description at run time (formerly RTTI)

Dynamic type creation (RTTC)

Implemented as system classes

Concept

Universal type identification

Each type kind corresponds to one RTTI description class

Type properties represented by attributes

Type creation via factory methods

Run Time Type Services (RTTS)

Page 48: Abap advanced

48

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

RTTS Class Hierarchy

CL_ABAP_TYPEDESCR

CL_ABAP_DATADESCR CL_ABAP_OBJECTDESCR

CL_ABAP_ELEMDESCR CL_ABAP_INTFDESCR

CL_ABAP_CLASSDESCR

CL_ABAP_COMPLEXDESCR

CL_ABAP_STRUCTDESCR CL_ABAP_TABLEDESCR

CL_ABAP_REFDESCR

Page 49: Abap advanced

49

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Principles of Types in ABAP

Type is well-defined by itstype object

For every type there is a run time type objectEvery type object correspondsto a type

Type object is instance of RTTS class

Type objectsAre immutableDescribe all properties of the typeCan be used instead of type name

Named types and elementary types aremanaged by the runtime system

TYPES: BEGIN OF struc,name TYPE string,age TYPE i,

END OF struc.

CL_ABAP_STRUCTDESCR

nameage

oo

struc

Page 50: Abap advanced

50

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

How to get a Type Object

Get type object by type name

Get type object from a data object

Get elementary types

DATA: dataType TYPE REF TO cl_abap_datadescr,

field(5) TYPE c.

dataType ?= cl_abap_typedescr=>describe_by_data( field ).

DATA: strucType TYPE REF TO cl_abap_structdescr.

structType ?= cl_abap_typedescr=>describe_by_name( 'SPFLI' ).

DATA: elemType TYPE REF TO cl_abap_elemdescr.

elemType = cl_abap_elemdescr=>get_i( ).

elemType = cl_abap_elemdescr=>get_c( 20 ).

Note, that type objects exist for all kinds of types, even for generic types.

Instead of calling get_i() or get_string() on class CL_ABAP_ELEMDESCR, youcould also call describe_by_name() passing ‚I‘ resp. ‚STRING‘ as argument.

Be careful when calling describe_by_name() with ‚C‘, ‚N‘, etc. as argument as this will return the (partly) generic types C, N, etc. which is probably not whatyou want.

Page 51: Abap advanced

51

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Working with Type Objects

Create a data object of a specific type using a type object

Casting of a field symbol using a type object

DATA: dref TYPE REF TO DATA,

c20Type TYPE REF TO cl_abap_elemdescr.

c20Type = cl_abap_elemdescr=>get_c( 20 ).

CREATE DATA dref TYPE HANDLE c20Type.

DATA: x20Type TYPE REF TO cl_abap_elemdescr.

FIELD-SYMBOLS: <fs> TYPE any.

x20Type = cl_abap_elemdescr=>get_x( 20 ).

ASSIGN dref->* TO <fs> CASTING TYPE HANDLE x20Type.

You can create a data object from a type object only, if the type isinstantiatable, that means, if the type objects doesn‘t represent a fully or partlygeneric type like DATA or C without length specification. In order to find out if a type is instantiatable, call method is_instantiatable() on the type object.

Page 52: Abap advanced

52

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Principles of Dynamic Type Creation

Dynamically created types areTransient (exist only for the lifetime of the internal mode)Program local (live only in roll area)Anonymous (no name, only accessible by type object)

Creation of composed data types onlyStructure typesTable typesReference types

Bottom-up approachCreate new types based on existing ones

Page 53: Abap advanced

53

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Implicit vs. Explicit Type Creation

Implicit type creationDeclarative approachOnly for table and reference types

Explicit Type creationProcedural approachFactory method CREATE( ) in RTTS classes

CREATE DATA dref TYPE TABLE OF type.

CREATE DATA dref TYPE REF TO type.

structType = CL_ABAP_STRUCTDESCR=>create( compTab ).

A type is implicitely created during creation of a data object, if the type doesn‘texist. This is comparable to the (static) definition of a data object withoutexplicit type specification as in

DATA itab TYPE TABLE OF linetype.The only difference is that in the first case type creation happens at run time, while in the second case it happens at compile time.

As in contrast to implicit type creation, explicit type creation is valid for all sortsof types, including structured types.

Note, that elementary types like C fields, P numbers etc. cannot be created. Conceptually, all elementary types already exist and can be accessed bycorresponding get_XXX( ) methods in CL_ABAP_ELEMDESCR. Consequently, CL_ABAP_ELEMDESCR has no factory method CREATE( ).

Page 54: Abap advanced

54

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Limitations of Dynamically Created Types

Every call of factory method CREATE( ) creates a new type

Types cannot be destroyedType object is garbage collected if there are no data objects of that typeanymore

Reuse of dynamically created types via factory method GET( ) (since 7.1)Same signature as createReturns type object with same propertiesCreates type if not existing yet

For GET( ) types are considered equal, ifTable types have the same line type and same table propertiesReference types have the same base typeStructure types have the same component names and types

Page 55: Abap advanced

55

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Dynamic Creation of Table Types

Line type mandatory, other parameters optional

CREATE_WITH_KEY( ) alternative factory for tables with multiple (secondary) keys

CLASS cl_abap_tabledescr DEFINITION ...

CLASS-METHODS create

IMPORTING

p_line_type TYPE REF TO cl_abap_datadescr

p_table_kind TYPE abap_tablekind DEFAULT tablekind_std

p_unique TYPE abap_bool DEFAULT abap_false

p_key TYPE abap_keydescr_tab OPTIONAL

p_key_kind TYPE abap_keydefkind DEFAULT keydefkind_default

RETURNING

value(p_result) TYPE REF TO cl_abap_tabledescr

RAISING

cx_sy_table_creation

Page 56: Abap advanced

56

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Dynamic Creation of Table Types

CLASS cl_abap_tabledescr DEFINITION ...

CLASS-METHODS create

IMPORTING

p_line_type TYPE REF TO cl_abap_datadescr

p_table_kind TYPE abap_tablekind

DEFAULT tablekind_std

p_unique TYPE abap_bool DEFAULT abap_false

p_key TYPE abap_keydescr_tab OPTIONAL

p_key_kind TYPE abap_keydefkind

DEFAULT keydefkind_default

RETURNING

value(p_result) TYPE REF TO cl_abap_tabledescr

RAISING

cx_sy_table_creation

Alternatives

tablekind_stdtablekind_sortedtablekind_hashed

Page 57: Abap advanced

57

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Dynamic Creation of Table Types

CLASS cl_abap_tabledescr DEFINITION ...

CLASS-METHODS create

IMPORTING

p_line_type TYPE REF TO cl_abap_datadescr

p_table_kind TYPE abap_tablekind

DEFAULT tablekind_std

p_unique TYPE abap_bool DEFAULT abap_false

p_key TYPE abap_keydescr_tab OPTIONAL

p_key_kind TYPE abap_keydefkind

DEFAULT keydefkind_default

RETURNING

value(p_result) TYPE REF TO cl_abap_tabledescr

RAISING

cx_sy_table_creationAlternativeskeydefkind_defaultkeydefkind_tablelinekeydefkind_user

Page 58: Abap advanced

58

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Dynamic Creation of Table Types

CLASS cl_abap_tabledescr DEFINITION ...

CLASS-METHODS create

IMPORTING

p_line_type TYPE REF TO cl_abap_datadescr

p_table_kind TYPE abap_tablekind

DEFAULT tablekind_std

p_unique TYPE abap_bool DEFAULT abap_false

p_key TYPE abap_keydescr_tab OPTIONAL

p_key_kind TYPE abap_keydefkind

DEFAULT keydefkind_default

RETURNING

value(p_result) TYPE REF TO cl_abap_tabledescr

RAISING

cx_sy_table_creation

Key fields forstructuredline types:

Alternativeskeydefkind_defaultkeydefkind_tablelinekeydefkind_user

name

Page 59: Abap advanced

59

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Example of Dynamic Table Type Creation

TYPES tableTypeTYPE SORTED TABLE OF spfliWITH UNIQUE KEY carrid connid.

LH 0400 6.162LH 0400 5.347QF 0005 1.000SQ 0866 1.625

CARRID CONNID DISTANCE ...

DATA: lineType TYPE REF TO cl_abap_structdescr,tableType TYPE REF TO cl_abap_tabledescr,key TYPE abap_keydescr_tab.

lineType ?= cl_abap_typedescr=>describe_by_name( 'SPFLI' ).

APPEND 'CARRID' TO key. APPEND 'CONNID' TO key.tableType = cl_abap_tabledescr=>create(

p_line_type = lineTypep_table_kind = cl_abap_tabledescr=>tablekind_sortedp_unique = abap_truep_key = key ).

Page 60: Abap advanced

60

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Example of Dynamic Table Type Creation

DATA: lineType TYPE REF TO cl_abap_structdescr,tableType TYPE REF TO cl_abap_tabledescr,key TYPE abap_keydescr_tab.

lineType ?= cl_abap_typedescr=>describe_by_name( 'SPFLI' ).

APPEND 'CARRID' TO key. APPEND 'CONNID' TO key.tableType = cl_abap_tabledescr=>create(

p_line_type = lineTypep_table_kind = cl_abap_tabledescr=>tablekind_sortedp_unique = abap_truep_key = key ).

CL_ABAP_STRUCTDESCR

distance:

oo

spflicarridconnid

oo

lineType

LH 0400 6.162LH 0400 5.347QF 0005 1.000SQ 0866 1.625

CARRID CONNID DISTANCE ...TYPES tableType

TYPE SORTED TABLE OF spfliWITH UNIQUE KEY carrid connid.

Page 61: Abap advanced

61

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Example of Dynamic Table Type Creation

DATA: lineType TYPE REF TO cl_abap_structdescr,tableType TYPE REF TO cl_abap_tabledescr,key TYPE abap_keydescr_tab.

lineType ?= cl_abap_typedescr=>describe_by_name( 'SPFLI' ).

APPEND 'CARRID' TO key. APPEND 'CONNID' TO key.tableType = cl_abap_tabledescr=>create(

p_line_type = lineTypep_table_kind = cl_abap_tabledescr=>tablekind_sortedp_unique = abap_truep_key = key ).

CL_ABAP_STRUCTDESCR

distance:

oo

spflicarridconnid

oo

CARRIDCONNID

keytab

LH 0400 6.162LH 0400 5.347QF 0005 1.000SQ 0866 1.625

CARRID CONNID DISTANCE ...TYPES tableType

TYPE SORTED TABLE OF spfliWITH UNIQUE KEY carrid connid.

lineType

Page 62: Abap advanced

62

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Example of Dynamic Table Type Creation

DATA: lineType TYPE REF TO cl_abap_structdescr,tableType TYPE REF TO cl_abap_tabledescr,key TYPE abap_keydescr_tab.

lineType ?= cl_abap_typedescr=>describe_by_name( 'SPFLI' ).

APPEND 'CARRID' TO key. APPEND 'CONNID' TO key.tableType = cl_abap_tabledescr=>create(

p_line_type = lineTypep_table_kind = cl_abap_tabledescr=>tablekind_sortedp_unique = abap_truep_key = key ).

CL_ABAP_STRUCTDESCR

distance:

oo

spflicarridconnid

oo

tableType

LH 0400 6.162LH 0400 5.347QF 0005 1.000SQ 0866 1.625

CARRID CONNID DISTANCE ...TYPES tableType

TYPE SORTED TABLE OF spfliWITH UNIQUE KEY carrid connid.

CL_ABAP_TABLEDESCRline_type o

key

lineType

CARRIDCONNID

keytab

Page 63: Abap advanced

63

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Dynamic Creation of Reference Types

Create a reference type from a base typeBase type may be class, interface or data type

Short cut for named base typesEasier to useMuch more efficient for object types if type description object not yetcreated

CLASS cl_abap_refdescr DEFINITION ...

CLASS-METHODS create

IMPORTING p_referenced_type TYPE REF TO cl_abap_typedescr

RETURNING value(p_result) TYPE REF TO cl_abap_refdescr

RAISING cx_sy_ref_creation.

CLASS-METHODS create_by_name

IMPORTING p_referenced_type_name TYPE csequence

RETURNING value(p_result) TYPE REF TO cl_abap_refdescr

RAISING cx_sy_ref_creation cx_sy_unknown_type.

Note that, when having class A, CL_ABAP_TYPEDESCR=>describe_by_name( 'A' ) returns the class, not thereference type to that class. Compare that to static definition of objectvariables: you must declare a variable v being of type REF TO A, not A itself.

The factory method create_by_name() is not just a convenience method thatsaves you retrieving the type object of the base type first. It's also a hugeperformance improvement for references to classes and interfaces, as gettingtype objects for them is rather expensive.

Page 64: Abap advanced

64

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Examples of Dynamic Reference Type Creation

TYPES: refToIType TYPE REF TO i,refToSomeClass TYPE REF TO cl_some_class.

DATA: baseType TYPE REF TO cl_abap_typedescr,refToIType TYPE REF TO cl_abap_refdescr,refToSomeClass TYPE REF TO cl_abap_refdescr.

baseType = cl_abap_elemdescr=>get_i( ).refToIType = cl_abap_refdescr=>create( baseType ).refToSomeClass = cl_abap_refdescr=>create_by_name( 'CL_SOME_CLASS' ).

123i:

CL_SOME_CLASS

Page 65: Abap advanced

65

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Examples of Dynamic Reference Type Creation

DATA: baseType TYPE REF TO cl_abap_typedescr,refToIType TYPE REF TO cl_abap_refdescr,refToSomeClass TYPE REF TO cl_abap_refdescr.

baseType = cl_abap_elemdescr=>get_i( ).refToIType = cl_abap_refdescr=>create( baseType ).refToSomeClass =

cl_abap_refdescr=>create_by_name( 'CL_SOME_CLASS' ).

CL_ABAP_ELEMDESCR

i_type

123i:

CL_SOME_CLASS baseType

TYPES: refToIType TYPE REF TO i,refToSomeClass TYPE REF TO cl_some_class.

Page 66: Abap advanced

66

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Examples of Dynamic Reference Type Creation

DATA: baseType TYPE REF TO cl_abap_typedescr,refToIType TYPE REF TO cl_abap_refdescr,refToSomeClass TYPE REF TO cl_abap_refdescr.

baseType = cl_abap_elemdescr=>get_i( ).refToIType = cl_abap_refdescr=>create( baseType ).refToSomeClass = cl_abap_refdescr=>create_by_name( 'CL_SOME_CLASS' ).

CL_ABAP_REFDESCRreferenced_type orefToIType

123i:

CL_SOME_CLASS

CL_ABAP_ELEMDESCR

i_type

baseType

TYPES: refToIType TYPE REF TO i,refToSomeClass TYPE REF TO cl_some_class.

Page 67: Abap advanced

67

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Examples of Dynamic Reference Type Creation

DATA: baseType TYPE REF TO cl_abap_typedescr,refToIType TYPE REF TO cl_abap_refdescr,refToSomeClass TYPE REF TO cl_abap_refdescr.

baseType = cl_abap_elemdescr=>get_i( ).refToIType = cl_abap_refdescr=>create( baseType ).refToSomeClass =

cl_abap_refdescr=>create_by_name( 'CL_SOME_CLASS' ).

CL_ABAP_REFDESCRreferenced_type o

refToSomeClass

cl_some_class

123i:

CL_SOME_CLASS

CL_ABAP_REFDESCRreferenced_type orefToIType

CL_ABAP_ELEMDESCR

i_type

baseType

TYPES: refToIType TYPE REF TO i,refToSomeClass TYPE REF TO cl_some_class.

Page 68: Abap advanced

68

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Dynamic Creation of Structured Types

Create a structured type from a component description tablecomponent table mandatorystrictness optional

CLASS cl_abap_structdescr DEFINITION ...

CLASS-METHODS create

IMPORTING

p_components TYPE component_table

p_strict TYPE abap_bool DEFAULT abap_true

RETURNING

value(p_result) TYPE REF TO cl_abap_structdescr

RAISING

cx_sy_struct_creation.

ABAP Objects namingconventionsenforced

Page 69: Abap advanced

69

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

NAME TYPE AS_INCLUDE SUFFIX TYPES: BEGIN OF personType,name TYPE string,age(3) TYPE n,

END OF personType.

DATA: personType TYPE REF TO cl_abap_structdescr,comp_tab TYPE cl_abap_structdescr=>component_table.

personType ?= cl_abap_typedescr=>describe_by_name( 'personType' ).comp_tab = personType->get_components( ).

Component Description Table

The component description table describes all components of a structure, where every line corresponds to the respective component.

Every component has at least a name and a type.

The name is subject to certain restrictions, e.g. there must not be two lineswith the same name. The degree of restrictions is controlled by the parameterp_strict when creating the structure. By default it is set to the same set of rulesthat apply to the definition of structures in ABAP-OO.

The type column contains the type of the respective component. The type isexpressed by a type object, as can be accessed/created via the RTTS framework.

Page 70: Abap advanced

70

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Component Description Table

DATA: personType TYPE REF TO cl_abap_structdescr,comp_tab TYPE cl_abap_structdescr=>component_table.

personType ?= cl_abap_typedescr=>describe_by_name( 'personType' ).comp_tab = personType->get_components( ).

personTypeCL_ABAP_STRUCTDESCR

component_table

NAME TYPE AS_INCLUDE SUFFIX TYPES: BEGIN OF personType,name TYPE string,age(3) TYPE n,

END OF personType.

Page 71: Abap advanced

71

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

DATA: personType TYPE REF TO cl_abap_structdescr,comp_tab TYPE cl_abap_structdescr=>component_table.

personType ?= cl_abap_typedescr=>describe_by_name( 'personType' ).comp_tab = personType->get_components( ).

comp_tab:NAME TYPE AS_INCLUDE SUFFIX TYPES:

BEGIN OF personType,name TYPE string,age(3) TYPE n,

END OF personType.

CL_ABAP_STRUCTDESCR

component_table

NAME

AGE

Component Description Table

personType

Page 72: Abap advanced

72

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

NAME TYPE AS_INCLUDE SUFFIX

EMPLOYEE

TYPES: BEGIN OF employeeType,employee TYPE personType,manager TYPE personType,

END OF employeeType.

DATA: personType TYPE REF TO cl_abap_structdescr,employeeType TYPE REF TO cl_abap_structdescr,comp_tab TYPE cl_abap_structdescr=>component_table,comp LIKE LINE OF comp_tab.

personType ?= cl_abap_typedescr=>describe_by_name( 'personType' ).comp-name = 'EMPLOYEE'. comp-type = personType. append comp to comp_tab.comp-name = 'MANAGER'. comp-type = personType. append comp to comp_tab.employeeType = cl_abap_structdescr=>create( comp_tab ).

Example of Dynamic Structure Type Creation

Page 73: Abap advanced

73

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

NAME TYPE AS_INCLUDE SUFFIX TYPES: BEGIN OF employeeType,employee TYPE personType,manager TYPE personType,

END OF employeeType.

EMPLOYEE

MANAGER

DATA: personType TYPE REF TO cl_abap_structdescr,employeeType TYPE REF TO cl_abap_structdescr,comp_tab TYPE cl_abap_structdescr=>component_table,comp LIKE LINE OF comp_tab.

personType ?= cl_abap_typedescr=>describe_by_name( 'personType' ).comp-name = 'EMPLOYEE'. comp-type = personType. append comp to comp_tab.comp-name = 'MANAGER'. comp-type = personType. append comp to comp_tab.employeeType = cl_abap_structdescr=>create( comp_tab ).

Example of Dynamic Structure Type Creation

Page 74: Abap advanced

74

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

NAME TYPE AS_INCLUDE SUFFIX TYPES: BEGIN OF employeeType,employee TYPE personType,manager TYPE personType,

END OF employeeType.

EMPLOYEE

MANAGER

employeeType

DATA: personType TYPE REF TO cl_abap_structdescr,employeeType TYPE REF TO cl_abap_structdescr,comp_tab TYPE cl_abap_structdescr=>component_table,comp LIKE LINE OF comp_tab.

personType ?= cl_abap_typedescr=>describe_by_name( 'personType' ).comp-name = 'EMPLOYEE'. comp-type = personType. append comp to comp_tab.comp-name = 'MANAGER'. comp-type = personType. append comp to comp_tab.employeeType = cl_abap_structdescr=>create( comp_tab ).

CL_ABAP_STRUCTDESCR

component_table

Example of Dynamic Structure Type Creation

Page 75: Abap advanced

75

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Exercise 3

Page 76: Abap advanced

76

SAP TechEd ‘07

Exception Handling

Advanced Programming Guidelines

Generic Programming

Page 77: Abap advanced

77

SAP TechEd ‘07

Principles of Exception HandlingException RaisingCatching ExceptionsDeclaration of ExceptionsDefinition of Exception ClassesResumable Exceptions

Page 78: Abap advanced

78

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Principles of Exception Handling 1/2

Look at software as a (layered) collection of services

In an error situation, a servicehas only limited knowledge about the (global) application contextis probably not able to take corrective measures

Best way to deal with error situationSignal what went wrong, passing along additional informationPass flow of control to a suitable handler which is able to react to that particular situationHandler may decide to abort or continue

RequirementsSeparation of normal coding from error handler codingSelective definition of handlers for certain errorsAutomatic abort of routine, that cannot provide promised service

Page 79: Abap advanced

79

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Principles of Exception Handling 2/2

Exception as an object of an exception classAttributes can store additional informationRefinement through inheritanceGrouping by using inheritance

Raising an exceptionCreation of exception objectPropagation along call chain until suitable handler is found(change of control flow)If no handler is found: short dump

Exceptions as part of signature of proceduresCallers know about exceptions they have to deal with

In principle comparable to Java, C++

Page 80: Abap advanced

80

SAP TechEd ‘07

Principles of Exception HandlingException RaisingCatching ExceptionsDeclaration of ExceptionsDefinition of Exception ClassesResumable Exceptions

Page 81: Abap advanced

81

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Raising Class-Based Exceptions

Raise exception with implicit object creation RAISE EXCEPTION TYPE cx_page_not_foundEXPORTING page = 'http://www.sap.com/shop/'.

DATA excp TYPE REF TO cx_page_not_found.CREATE OBJECT excp

EXPORTING page = 'http://www.sap.com/shop/'.RAISE EXCEPTION excp.

x = 1 / 0. "creates exception cx_sy_zerodivide

Raise exception with explicit object creation or re-raise a caught exception

Exception raised by kernel (runtime exception)

Exception object contains additional information, e.g. page, explaining text and position where exception occurred.

Page 82: Abap advanced

82

SAP TechEd ‘07

Principles of Exception HandlingException RaisingCatching ExceptionsDeclaration of ExceptionsDefinition of Exception ClassesResumable Exceptions

Page 83: Abap advanced

83

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Catching Class-Based Exceptions

Syntactical construct: TRY..ENDTRY

DATA excp TYPE REF TO cx_sy_file_open_mode.TRY.

CATCH cx_sy_file_open_mode INTO excp.

CATCH cx_sy_file_access_error

ENDTRY.

OPEN DATASET file FOR OUTPUT IN BINARY MODE.TRANSFER xbuffer TO file.CLOSE DATASET file.WRITE: 'Buffer successfully written'.

WRITE: 'File', excp->filename, 'is not open'.

WRITE: 'Other file IO exception occurred'.

Consists ofExactly one protected code areaOne or more exception handlers

Page 84: Abap advanced

84

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

TRY.

Protected Area

Protected areaAll statements between TRY and first CATCHOnly exceptions that occur in protected area can be handled

Handler code is not protectedBut TRY constructs can be nested

CATCH cx_e1 ... cx_eN [ INTO excp1 ].

CATCH cx_f1 ... Cx_fM [ INTO excp2 ].

...ENDTRY.

"– handler code for exceptions cx_e1 ..cx_eN

"– handler code for exceptions cx_f1 ..cx_fM

"– any statements

Page 85: Abap advanced

85

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Exception Handlers

Exception handlers (CATCH clauses)Are checked from top to bottomEach can handle one or more exceptions

Optional access to exception object by INTO clause

TRY."– any statements

CATCH cx_e1 ... cx_eN [ INTO excp1 ].

CATCH cx_f1 ... cx_fN [ INTO excp2 ].

...ENDTRY.

"– handler code for exceptions cx_e1 ..cx_eN

"– handler code for exceptions cx_f1 ..cx_fN

Page 86: Abap advanced

86

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Grouping by Polymorphism

Superclasses can be used in CATCH clauses to catch all exceptions of any subtype

Order of clauses is important

Order must be from 'special' to more 'general' exception CX_ROOT

CX_PAGE_NOT_FOUND

CX_SY_ARITHMETIC_ERROR

CX_SY_ZERODIVIDE CX_SY_ARITHMETIC_OVERFLOW

Page 87: Abap advanced

87

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Automatic Exception Propagation

METHOD retrieve. "IMPORTING a_page TYPE string … RAISE EXCEPTION TYPE cx_page_not_found …

ENDMETHOD.

METHOD show. "IMPORTING a_page TYPE stringTRY.

retrieve( a_page )." -- More normal coding

CATCH cx_some_exception." -- Error handling for some exception.

CATCH cx_other_exception." -- Error handling for other exception.

ENDTRY.ENDMETHOD.

TRY.dispatcher->show( a_page )." -- More normal coding

CATCH cx_page_not_found cx_misformed_url." -- Error handling.

ENDTRY.

Page 88: Abap advanced

88

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

How to Find the Right Exception Handler

Exceptionoccurred

Inside protected

area?

Look for handler in corresponding

TRY-block

Handlerfound?

Go up call hierarchyand look for outer

TRY-block

TRY-blockfound?

yes

no

yes

no

RuntimeError

no

Processhandler

code

Go to end of handler'sTRY-block

yes

Page 89: Abap advanced

89

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

TRY."– any statements

CATCH cx_e1 ... cx_eN [ INTO excp1 ].

...CLEANUP [ INTO excp ]. "- optional

ENDTRY.

"– handler code for exceptions cx_e1 ..cx_eN

"– statements

How to Guarantee a Consistent State

ProblemProcedures are left prematureObjects / application might be in an inconsistent stateExample: allocated resources

SolutionIntroduction of (optional) CLEANUP clause

Page 90: Abap advanced

90

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Example CLEANUP Clause

METHOD retrieve. "IMPORTING a_page TYPE string … RAISE EXCEPTION TYPE cx_page_not_found …

ENDMETHOD.

METHOD show. "IMPORTING a_page TYPE stringTRY.

retrieve( a_page ).CATCH cx_some_exception.

" -- Error handling for some exception.CATCH cx_other_exception.

" -- Error handling for other exception.ENDTRY.

ENDMETHOD.

TRY.dispatcher->show( a_page ).

CATCH cx_page_not_found cx_misformed_url." -- Error handling.

ENDTRY.

METHOD show. "IMPORTING a_page TYPE stringTRY.

retrieve( a_page ).CATCH cx_some_exception.

" -- Error handling for some exception.CATCH cx_other_exception.

" -- Error handling for other exception.

ENDTRY.ENDMETHOD.

METHOD show. "IMPORTING a_page TYPE stringTRY.

retrieve( a_page ).CATCH cx_some_exception.

" -- Error handling for some exception.CATCH cx_other_exception.

" -- Error handling for other exception.

ENDTRY.ENDMETHOD.

METHOD show. "IMPORTING a_page TYPE stringTRY.

retrieve(a_page).CATCH cx_some_exception.

" -- Error handling for some exception.CATCH cx_other_exception.

" -- Error handling for other exception.

ENDTRY.ENDMETHOD.

CLEANUP." -- Free internal resources.

Page 91: Abap advanced

91

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

CLEANUP Clause

CLEANUP clause is processed if and only if exceptionHas occurred

Is not caught in current TRY – construct

Is going to be caught somewhere above in call hierarchy

Technically spoken CLEANUP clause is processed during unwinding of the stack

At the end of CLEANUP clause, execution continues with next higher CLEANUP clause or handler code respectively

CLEANUP clause must not be left abnormallyNo use of RETURN, EXIT, CONTINUE ... to leave the clause

Exceptions inside of the CLEANUP clause must be handled locally

Page 92: Abap advanced

92

SAP TechEd ‘07

Principles of Exception HandlingException RaisingCatching ExceptionsDeclaration of ExceptionsDefinition of Exception ClassesResumable Exceptions

Page 93: Abap advanced

93

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Declaring Exceptions

ProblemHow do users of a procedure know which exceptions to expect?

SolutionExceptions that are not handled inside of the procedure are part of the procedure's signature

METHODS: show IMPORTING a_page TYPE stringRAISING cx_page_not_found.

BenefitsUsers have only to deal with exceptions mentioned in a procedure's signatureCompiler can check if an exception is either handled inside of aprocedure or declared to leave it

Page 94: Abap advanced

94

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

RAISING Clause

Declaration in subroutines (forms), function modules and methods

... RAISING cx_e1 cx_e2 ... cx_eN

Each class mentioned in RAISING clause implies all subclasses

Compiler / extended syntax check warns if an exception is neither handled nor declared

Compiler warning instead of error to ease change processAt runtime a special exception is thrown (cx_sy_no_handler)if undeclared exception leaves procedure Original exception is no longer active (cannot be caught any more)

Page 95: Abap advanced

95

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Exceptions in Procedure Declarations

Use class-based exceptions

How to declare exceptions in class / function builder

Page 96: Abap advanced

96

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Limitations of Static Checking (1)

Some exceptions may occur anywhere, but are hard to be handled locally

Typical examples: resource limitation and global errors (e.g. cx_sy_too_many_files, cx_sy_no_more_memory)

Forcing the user to declare or catch such exceptions would be counter-productive

Either procedures get cluttered with exception declarationsOr users catch exceptions without having a proper handler

Better solution: there are exceptions that don't need to be declared

Compiler doesn't check if exception is handled (no static check at compile time)Runtime system doesn't check if exception was declared for a procedure if exceptions leaves it (no dynamic check at runtime)

Consequence: users have to be aware that these exceptions may occur anywhere

Page 97: Abap advanced

97

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Limitations of Static Checking (2)

For some exceptions, users can ensure that they will not occur

They know(!) what they are doing or they can avoid error conditions beforehandTypical examples: parameter constraints (e.g. cx_sy_zerodivide,cx_misformed_url)

Forcing the user to declare or catch such exceptions would be counter-productive

Leads to empty handlers just to calm compiler down

Problem: what happens, if the exception does occur?

Solution: there are exceptions that must be declared if they can occur but they are not statically checked

Compiler doesn't check if exception is handledRuntime system does check if the exception was declared if it tries to leave the procedure

Consequence: if user was wrong (exception leaves procedure) an exception is thrown (cx_sy_no_handler)

Page 98: Abap advanced

98

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Exception Class Hierarchy

Three categories of exceptions

Signaturestatically checked

by compilerand dynamically

at runtime

Signaturechecked

only at runtime

Not insignature,

never checked

CX_ROOT

CX_DYNAMIC_CHECK CX_NO_CHECKCX_STATIC_CHECK

All exceptions are derived from corresponding classes

Page 99: Abap advanced

99

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Exception Class Hierarchy

Signaturestatically checked

by compilerand dynamically

at runtime

Signaturechecked

only at runtime

CX_ROOT

CX_DYNAMIC_CHECK CX_NO_CHECKCX_STATIC_CHECK

Can be used in RAISING clause

Not insignature

never checked

Page 100: Abap advanced

100

SAP TechEd ‘07

Principles of Exception HandlingException RaisingCatching ExceptionsDeclaration of ExceptionsDefinition of Exception ClassesResumable Exceptions

Page 101: Abap advanced

101

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Exception Classes: Methods and Attributes

Each exception class can define its own attributesAttributes can be of any typeAre preferably read-only

Methods inherited from cx_rootget_source_position:

returns position where exception has been raisedget_text, get_longtext:

returns textual description of exception(get_longtext available with SAP_BASIS 620)

Automatic generation of constructor in global exception classes

One optional parameter for each non-private attribute

Page 102: Abap advanced

102

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Chaining of Exceptions

Attribute previous:Enables chaining of exceptions

Classname CX_PAGE_NOT_FOUND

Previous

CX_SY_NO_HANDLER

Page http://www.sap.com/shop/

TextidCX_PAGE_NOT_FOUND

Example: undeclared exception leaves procedure

Exception cx_sy_no_handler is raised

Chaining can be employed explicitly

RAISE EXCEPTION TYPE cx_some_exception

EXPORTING previous = caught_exception.

Page 103: Abap advanced

103

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Exception Texts

Attribute textid:

Invalid account of customer MichaelNo document at URL http://www.sap.com/shop/

'No documentat URL &PAGE&'Page http://www.sap.com/shop/

Textid

CX_PAGE_NOT_FOUND

Method get_text, get_longtext:Returns textual description of the exception

Points to textual description of the exception

Occurrences of ‘&ATTRIBUTE&' in text are substituted by attribute values

'No documentat URL &PAGE&'

'No document at URL &PAGE&'

Page 104: Abap advanced

104

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Exception Builder

Substituted by attribute value

Default exception id has same name as

exception class

Page 105: Abap advanced

105

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Multiple Exception Texts

They can be used to differentiate between related exceptions

No need to define separate exception classes for slight variantsShould be really related

– all attributes have same meaning for all id'sHandlers usually will not differentiate between id's

Raise exception with different textRAISE EXCEPTION TYPE cx_sy_file_positionEXPORTINGtextid = cx_sy_file_position=>tell_error ...

Page 106: Abap advanced

106

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Exercise 4

Page 107: Abap advanced

107

SAP TechEd ‘07

Principles of Exception HandlingException RaisingCatching ExceptionsDeclaration of ExceptionsDefinition of Exception ClassesResumable Exceptions

Page 108: Abap advanced

108

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Motivation for Resumable Exceptions

Situations where exception paradigm is difficult to useMass data processing

– error in sub-task should not terminate complete processing

Collecting errors– check mode should collect all errors

Resumption after error correction– problem has been fixed, service sould continue (e.g. authority check)

Solution: Resumable ExceptionsNo automatic termination of service

– Technically: no unwinding of the stack

Handler can decide whether to terminate service or to continueService must be prepared for resumptionServices based on services, so all levels must agree

Page 109: Abap advanced

109

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Prerequisites for Resumable Exceptions

Resumption is possible ifException is raised as resumableException is propagated as resumable (in RAISING clause)Handler chooses resumption

“Resumability”Is not a property of the exception class, but of a single exceptionobjectCan get lost if not propagated as resumableCan be checked by evaluation of attribute is_resumable

Page 110: Abap advanced

110

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Raising Resumable Exceptions

Signaler of exception allows resumption with

RAISE RESUMABLE EXCEPTION TYPE cx [ EXPORTING ... ]

Signaler must be prepared that statement might return (dependent of the handler)

Be extremely careful with no-check exceptions

RAISE RESUMABLE EXCEPTION excp_obj

Page 111: Abap advanced

111

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Handling Resumable Exceptions

Prerequisite for resumption: context is keptCATCH unwinds the stackCLEANUP blocks get processed

New CATCH clause

CATCH BEFORE UNWIND cx_1 ... cx_n [ INTO excp ]

PropertiesUsed in the same way as simple CATCH clausesSame semantics, however, context is keptUnwinding of stack is deferred until handler is finishedCLEANUPs are processed when unwinding the stack

Page 112: Abap advanced

112

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Resumption

Handler may resume executionJump back to where the exception was raised (statement after RAISE)No unwinding of the stackCLEANUP blocks between signaler and handler are not processed

Statement

RESUME

PrerequisitesOnly allowed in CATCH BEFORE UNWIND blockException must be resumable, else runtime error CX_SY_ILLEGAL_HANDLER

Page 113: Abap advanced

113

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Example with resumption

METHOD m2. … RAISE RESUMABLE EXCEPTION TYPE cx_some_excp ……

ENDMETHOD.

TRY.CALL METHOD m1 …

CATCH BEFORE UNWIND cx_some_excp INTO ex.IF ex->is_resumable = abap_true.

… RESUME.ENDIF.

ENDTRY.

METHOD m1.TRY.

CALL METHOD m2 …CATCH cx_other_exception.

" -- Error handling for other exception.CLEANUP.

" – fixing things upENDTRY.

ENDMETHOD.

Page 114: Abap advanced

114

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Example without resumption

METHOD m2. … RAISE RESUMABLE EXCEPTION TYPE cx_some_excp ……

ENDMETHOD.

TRY.CALL METHOD m1 …

CATCH BEFORE UNWIND cx_some_excp INTO ex.…

ENDTRY.…

METHOD m1.TRY.

CALL METHOD m2 …CATCH cx_other_exception.

" -- Error handling for other exception.CLEANUP.

" – fixing things upENDTRY.

ENDMETHOD.

Page 115: Abap advanced

115

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Declaring Resumable Exceptions

ProblemHow do users of a procedure know which of the expected exceptions may be resumable?

Solution“Resumability” must be declared in procedures signature

Clause used for methods, function modules, formsRESUMABLE(cx) means: cx may be resumable, it doesn’t need toControls propagation of exceptions of type CX_STATIC_CHECK and CX_DYNAMIC_CHECK (CX_NO_CHECK are always propagated automatically)Actual exception loses its “resumability” if not propagated as resumableOnce the property is lost, it cannot be reestablished

... RAISING cx_e1 | RESUMABLE (cx_e1) ...

Page 116: Abap advanced

116

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Exercise 5

Page 117: Abap advanced

117

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Appendix

Page 118: Abap advanced

118

SAP TechEd ‘07

Appendix: MVC in Web DynproAppendix: ABAP Type Hierarchy

Page 119: Abap advanced

119

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Web Dynpro Component Architecture

Business Logic

(Models)

ComponentController

Model 1

Model 2

Contains Usagedeclarations

Usa

ge d

ecla

ratio

ns

W e b D y n p r o C o m p o n e n t

Components

CustomController

Component Interface

InterfaceController

Interface view

Window WindowController

ViewLayout

ViewController

M

M

M

M

M

Interface view

SAP Web Dynpro uses principles of MVC paradigm

Controllers handle the user input and steers the application

Views define the layout

Models hold and provide the business logic

Web Dynpro’s use of the MVC design paradigmSAP has made several important changes to the standard MVC design paradigm:

– Standard MVC allows a model to directly notify a view that it has changed. This has not been implemented in Web Dynpro.

– Standard MVC allows for nested view controllers. This is not permitted in Web Dynpro.

– SAP has extended the design concept by adding an aggregation unit known as a component. The component is both the unit of application development and application reuse.

Page 120: Abap advanced

120

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

types

data types objecttypes

elementary data types

interfacesclassescomplex data types

structuretypes

tabletypes

reference types

fixed length

variable length

data reference

types

object reference

types

ABAP Type Hierarchy

Page 121: Abap advanced

121

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Further Information

SAP Public Web:SAP Developer Network (SDN): www.sdn.sap.comBusiness Process Expert (BPX) Community: www.bpx.sap.com

Related Workshops/Lectures at SAP TechEd 2007CD256, Efficient Database Programming, Hands-on 2h CD354, Advanced Internal Table Programming Using Secondary Keys,

Hands-on 2hCD252, ABAP Troubleshooting, Hands-on 4hCD253, ABAP Workbench Power Usage, Hands-on 2hCD250, ABAP and XML, Hands-on 4hCD200, News in ABAP – Concepts to Further Increase the Power of

ABAP Development, Lecture 2h

Related SAP Education and Certification Opportunitieshttp://www.sap.com/education/

Page 122: Abap advanced

122

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

SDN Subscriptions Program

The SDN Subscriptions Program introduces the SAP NetWeaver, Development Subscription for individual developers. Available for purchase in Germany and the United States.

Subscription gives you one year access to …SAP NetWeaver platform software, patches, and updatesDevelopment license for SAP NetWeaver to evaluate, develop and test Standard software maintenanceOnline sessions from SAP TechEdAccess to SAP Enterprise Services Workplace for testingPremium presence in forums

Purchase the SAP NetWeaver, Development Subscription today at the SAP Community Clubhouse, or online at https://www.sdn.sap.com/irj/sdn/devsubVisit us at the Community Clubhouse, show us you are a subscriber, and get a gift!

Page 123: Abap advanced

123

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

THANK YOU FOR YOURATTENTION !

QUESTIONS – SUGGESTIONS – DISCUSSION

Q & A

Page 124: Abap advanced

124

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Please complete your session evaluation.

Be courteous — deposit your trash, and do not take the handouts for the following session.

Feedback

Thank You !

Page 125: Abap advanced

125

SAP TechEd ‘07SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / 125

SAP Certifications Related to SAP TechEd Topics

Topic Exam Level Certificate Title Solution BasisABAP Professional SAP Certified Development Professional - ABAP System Interfaces with

SAP NetWeaver 7.0SAP NetWeaver 7.0

ABAP Professional SAP Certified Development Professional - ABAP System Interfaces with SAP NetWeaver 7.0

SAP NetWeaver 7.0

ABAP Associate SAP Certified Development Consultant – ABAP Dev with NetWeaver 2004 SAP NetWeaver 2004

ABAP Associate SAP Certified Development Associate – ABAP with SAP NetWeaver 7.0 SAP NetWeaver 7.0

ADM Professional SAP Certified Technology Professional – NetWeaver 7.0 Platform SAP NetWeaver 7.0

ADM Professional SAP Certified Technology Professional – NetWeaver 7.0 Security SAP NetWeaver 7.0

ADM Associate SAP Certified Technology Associate – SAP Web AS Platform with Oracle SAP NetWeaver 2004

ADM Associate SAP Certified Technology Consultant – NetWeaver 7.0 SysAd with Oracle SAP NetWeaver 7.0

BI Associate Solution Consultant SAP NetWeaver ’04s – SAP BI SAP NetWeaver 7.0

E2E Associate SAP Certified E2E Application Management Expert – Change Control Mgmt SAP NetWeaver 7.0

E2E Associate SAP Certified E2E Application Management Expert – Root Cause Analysis SAP NetWeaver 7.0

Java Professional SAP Certified Development Professional – JAVA with NetWeaver 7.0 SAP NetWeaver 7.0

Java Associate SAP Certified Development Associate – JAVA with NetWeaver 7.0 SAP NetWeaver 7.0

MDM Associate SAP Certified Application Associate – Master Data Management 5.5 (SP04) SAP NetWeaver 2004

SM Associate Solution Consultant SAP Solution Manager 4.0 – Implementation Tools SAP NetWeaver 7.0

SOA Associate SAP Certified Associate Enterprise Architect Enterprise SOA

XI Associate Certification Development Consultant SAP NetWeaver 2004s SAP NetWeaver 7.0

For a complete listing of certifications, please go to www.sap.com/services/education/certification

Page 126: Abap advanced

126

SAP TechEd ‘07

© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

Copyright 2007 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, Excel, 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, System i, System i5, System p, System p5, System x, System z, System z9, z/OS, AFP, Intelligent Miner, WebSphere, Netfinity, Tivoli, Informix, i5/OS, POWER, POWER5, POWER5+, OpenPower and PowerPC are trademarks or registered trademarks of IBM Corporation.

Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either trademarks or registered trademarks of Adobe Systems Incorporated 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.

The information in this document is proprietary to SAP. No part of this document may be reproduced, copied, or transmitted in any form or for any purpose without the express prior written permission of SAP AG.

This document is a preliminary version and not subject to your license agreement or any other agreement with SAP. This document contains only intended strategies, developments, and functionalities of the SAP® product and is not intended to be binding upon SAP to any particular course of business, product strategy, and/or development. Please note that this document is subject to change and may be changed by SAP at any time without notice.

SAP assumes no responsibility for errors or omissions in this document. SAP does not warrant the accuracy or completeness of the information, text, graphics, links, or other items contained within this material. This document is provided without a warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability, fitness for a particular purpose, or non-infringement.

SAP shall have no liability for damages of any kind including without limitation direct, special, indirect, or consequential damages that may result from the use of these materials. This limitation shall not apply in cases of intent or gross negligence.

The statutory liability for personal injury and defective products is not affected. SAP has no control over the information that you may access through the use of hot links contained in these materials and does not endorse your use of third-party Web pages nor provide any warranty whatsoever relating to third-party Web pages.