O slideshow foi denunciado.
Utilizamos seu perfil e dados de atividades no LinkedIn para personalizar e exibir anúncios mais relevantes. Altere suas preferências de anúncios quando desejar.
SAP TechEd ‘07 
CD350 
Advanced 
ABAP Programming 
1
SAP TechEd ‘07 
This presentation outlines our general product direction and should 
not be relied on in making a purchase...
SAP TechEd ‘07 
Development Architect, SAP AG 
3 
Contributing Speakers 
Frank Bertelsmeier 
Senior Developer, SAP AG 
Rol...
SAP TechEd ‘07 
As a result of this workshop, you will be able to: 
„ Utilize design aspects how to write reusable service...
SAP TechEd ‘07 
Advanced Programming Guidelines 
Generic Programming 
Exception Handling 
5
SAP TechEd ‘07 
How to Organize your Software? 
How to Accomplish Reuse? 
ABAP Programming Recommendations 
6
SAP TechEd ‘07 
Software Architecture Principles 
Defines software (like an ABAP application) 
to be decomposed and organi...
SAP TechEd ‘07 
Assign the components of a software to 
different concerns or layers of abstraction 
(partioning) and refl...
SAP TechEd ‘07 
Example for Software-layer Architecture 
Application Services 
9 
© SAP AG 2007, SAP TechEd ’07 / Session ...
SAP TechEd ‘07 
Separation of Presentation, Business logic and Persistence 
„ Separate presentation logic from application...
SAP TechEd ‘07 
Model View Controller (MVC) 
MVC for decoupling presentation and application logic 
Generates the applicat...
SAP TechEd ‘07 
Separation of Presentation Logic – MVC for Classic Dynpro 
GUI Status GUI Functions 
12 
Class Pool 
Local...
SAP TechEd ‘07 
Decoupling and Law of Demeter (LoD) 
Minimize coupling of components: Law of demeter 
Each component shoul...
SAP TechEd ‘07 
How to Organize your Software? 
How to Accomplish Reuse? 
ABAP Programming Recommendations 
14
SAP TechEd ‘07 
Don’t repeat, use parts and knowledge of existing software 
„ Reuse increases efficiency in software devel...
SAP TechEd ‘07 
Good modularization is basis for reuse 
„ Identify modules: One self-contained concept / concern / aspect ...
SAP TechEd ‘07 
How to Organize your Software? 
How to Accomplish Reuse? 
ABAP Programming Recommendations 
17
SAP TechEd ‘07 
Reusable Services in ABAP Objects 
How to adapt these criteria in ABAP? 
„ Use ABAP Objects 
– OO modeling...
SAP TechEd ‘07 
ABAP Programming Recommendations 
„ Defensive programming: Start as restrictive as possible and ease the 
...
SAP TechEd ‘07 
Development Life Cycle 
System Analysis 
& Design 
Ensure quality and reliability by regularly testing you...
SAP TechEd ‘07 
Static Checks: Code Inspector 
21 
© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 
Code inspection fro...
SAP TechEd ‘07 
ABAP Unit tests are implemented as local ABAP Objects 
classes in the ABAP program that contains the teste...
SAP TechEd ‘07 
23 
ABAP Unit – Result Display 
© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 
„ At the end of an ABA...
SAP TechEd ‘07 
ABAP Editor – Code Completion 
Code Completion provides easy access to services 
Code Completion 
„ Sugges...
SAP TechEd ‘07 
ABAP Editor – Code Completion Invocation 
„ Context-sensitive code completion (CTRL+SPACE) 
– Fields (vari...
SAP TechEd ‘07 
ABAP Programming Guidelines – Summary 
Writing modern ABAP means: 
„ Keep your coding structured and modul...
SAP TechEd ‘07 
Exercise 1 
27 
© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
SAP TechEd ‘07 
Advanced Programming Guidelines 
Generic Programming 
Exception Handling 
28
SAP TechEd ‘07 
Basic Generic Concepts 
Dynamic Statements 
Dynamic Type Creation 
29
SAP TechEd ‘07 
Basics of Generic Programming 
Generic Programming 
„ Coding is able to deal with more generally typed dat...
SAP TechEd ‘07 
A generic type unites a set of types and – like a non-generic type – 
defines a set of operations be used ...
SAP TechEd ‘07 
Generic Types 
Generic type specification used for 
„ Parameters 
METHOD foo_1 IMPORTING p1 TYPE any. 
......
SAP TechEd ‘07 
Field Symbols 
Field symbols 
„ Aliases for existing data fields (or parts of them) 
„ Assigned at run tim...
SAP TechEd ‘07 
LargeField(10) TYPE C VALUE '1234567890', 
TypeName(7) TYPE C VALUE 'MY_TYPE', 
SomeType TYPE REF TO cl_ab...
SAP TechEd ‘07 
Data references are pointers to data objects 
„ Using non-generic reference types 
DATA iref TYPE REF TO t...
SAP TechEd ‘07 
Assigning a data reference variable 
GET REFERENCE OF DataObject INTO dref 
CREATE DATA dref TYPE | LIKE ....
SAP TechEd ‘07 
Dynamic Creation of Data Objects 
37 
TYPES: BEGIN OF struc, 
a TYPE i, 
b TYPE c LENGTH 8, 
END OF STRUC....
SAP TechEd ‘07 
Basic Generic Concepts 
Dynamic Statements 
Dynamic Type Creation 
38
SAP TechEd ‘07 
Statements usually use arguments that refer to names of entities 
defined in the ABAP code or in a reposit...
SAP TechEd ‘07 
Entities that statements may specify dynamically include 
„ Fields 
„ Types 
„ Structure components 
„ For...
SAP TechEd ‘07 
Dynamic Field Specification 
Refer dynamically to a field or a database table 
„ ASSIGN (field) TO … 
„ SE...
SAP TechEd ‘07 
Dynamic Type Specification 
Refer dynamically to local types or data dictionary types 
„ ASSIGN ... CASTIN...
SAP TechEd ‘07 
Dynamic Component Specification 
Refer dynamically to structure components 
„ SORT ... BY (comp1) ... (com...
SAP TechEd ‘07 
Dynamic Clause Specification 
Include statement clauses dynamically with internal tables 
„ SELECT (fieldl...
SAP TechEd ‘07 
Exercise 2 
45 
© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
SAP TechEd ‘07 
Basic Generic Concepts 
Dynamic Statements 
Dynamic Type Creation 
46
SAP TechEd ‘07 
Run Time Type Services (RTTS) 
Functionality 
Type identification and description at run time (formerly RT...
SAP TechEd ‘07 
48 
RTTS Class Hierarchy 
CL_ABAP_REFDESCR 
© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 
CL_ABAP_TY...
SAP TechEd ‘07 
Principles of Types in ABAP 
„ Are immutable 
„ Describe all properties of the type 
„ Can be used instead...
SAP TechEd ‘07 
DATA: strucType TYPE REF TO cl_abap_structdescr. 
structType ?= cl_abap_typedescr=>describe_by_name( 'SPFL...
SAP TechEd ‘07 
Create a data object of a specific type using a type object 
DATA: dref TYPE REF TO DATA, 
c20Type TYPE RE...
SAP TechEd ‘07 
Principles of Dynamic Type Creation 
„ Transient (exist only for the lifetime of the internal mode) 
„ Pro...
SAP TechEd ‘07 
Implicit vs. Explicit Type Creation 
„ Declarative approach 
„ Only for table and reference types 
CREATE ...
SAP TechEd ‘07 
Limitations of Dynamically Created Types 
Every call of factory method CREATE( ) creates a new type 
Types...
SAP TechEd ‘07 
Dynamic Creation of Table Types 
CLASS cl_abap_tabledescr DEFINITION ... 
CLASS-METHODS create 
IMPORTING ...
SAP TechEd ‘07 
Dynamic Creation of Table Types 
CLASS cl_abap_tabledescr DEFINITION ... 
p_line_type TYPE REF TO cl_abap_...
SAP TechEd ‘07 
Dynamic Creation of Table Types 
CLASS cl_abap_tabledescr DEFINITION ... 
p_line_type TYPE REF TO cl_abap_...
SAP TechEd ‘07 
Dynamic Creation of Table Types 
CLASS cl_abap_tabledescr DEFINITION ... 
p_line_type TYPE REF TO cl_abap_...
SAP TechEd ‘07 
Example of Dynamic Table Type Creation 
59 
CARRID CONNID DISTANCE ... 
© SAP AG 2007, SAP TechEd ’07 / Se...
SAP TechEd ‘07 
Example of Dynamic Table Type Creation 
CARRID CONNID DISTANCE ... 
DATA: lineType TYPE REF TO cl_abap_str...
SAP TechEd ‘07 
Example of Dynamic Table Type Creation 
CARRID CONNID DISTANCE ... 
DATA: lineType TYPE REF TO cl_abap_str...
SAP TechEd ‘07 
Example of Dynamic Table Type Creation 
CARRID CONNID DISTANCE ... 
DATA: lineType TYPE REF TO cl_abap_str...
SAP TechEd ‘07 
Dynamic Creation of Reference Types 
CLASS cl_abap_refdescr DEFINITION ... 
CLASS-METHODS create 
IMPORTIN...
SAP TechEd ‘07 
Examples of Dynamic Reference Type Creation 
64 
123 
i: 
CL_SOME_CLASS 
© SAP AG 2007, SAP TechEd ’07 / S...
SAP TechEd ‘07 
Examples of Dynamic Reference Type Creation 
TYPES: 
refToIType TYPE REF TO i, 
refToSomeClass TYPE REF TO...
SAP TechEd ‘07 
Examples of Dynamic Reference Type Creation 
123 
DATA: baseType TYPE REF TO cl_abap_typedescr, 
refToITyp...
SAP TechEd ‘07 
Examples of Dynamic Reference Type Creation 
CL_ABAP_REFDESCR 
referenced_type o 
refToSomeClass 
DATA: ba...
SAP TechEd ‘07 
Dynamic Creation of Structured Types 
CLASS cl_abap_structdescr DEFINITION ... 
CLASS-METHODS create 
IMPO...
SAP TechEd ‘07 
Component Description Table 
NAME TYPE AS_INCLUDE SUFFIX TYPES: 
69 
© SAP AG 2007, SAP TechEd ’07 / Sessi...
SAP TechEd ‘07 
Component Description Table 
NAME TYPE AS_INCLUDE SUFFIX TYPES: 
BEGIN OF personType, 
name TYPE string, 
...
SAP TechEd ‘07 
Component Description Table 
comp_tab: 
NAME TYPE AS_INCLUDE SUFFIX TYPES: 
DATA: personType TYPE REF TO c...
SAP TechEd ‘07 
Example of Dynamic Structure Type Creation 
NAME TYPE AS_INCLUDE SUFFIX 
EMPLOYEE 
72 
© SAP AG 2007, SAP ...
SAP TechEd ‘07 
Example of Dynamic Structure Type Creation 
NAME TYPE AS_INCLUDE SUFFIX TYPES: 
73 
© SAP AG 2007, SAP Tec...
SAP TechEd ‘07 
Example of Dynamic Structure Type Creation 
NAME TYPE AS_INCLUDE SUFFIX TYPES: 
CL_ABAP_STRUCTDESCR 
compo...
SAP TechEd ‘07 
Exercise 3 
75 
© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
SAP TechEd ‘07 
Advanced Programming Guidelines 
Generic Programming 
Exception Handling 
76
SAP TechEd ‘07 
Principles of Exception Handling 
Exception Raising 
Catching Exceptions 
Declaration of Exceptions 
Defin...
SAP TechEd ‘07 
Principles of Exception Handling 1/2 
Look at software as a (layered) collection of services 
In an error ...
SAP TechEd ‘07 
Principles of Exception Handling 2/2 
Exception as an object of an exception class 
„ Attributes can store...
SAP TechEd ‘07 
Principles of Exception Handling 
Exception Raising 
Catching Exceptions 
Declaration of Exceptions 
Defin...
SAP TechEd ‘07 
Raising Class-Based Exceptions 
Raise exception with implicit object creation 
RAISE EXCEPTION TYPE cx_pag...
SAP TechEd ‘07 
Principles of Exception Handling 
Exception Raising 
Catching Exceptions 
Declaration of Exceptions 
Defin...
SAP TechEd ‘07 
Catching Class-Based Exceptions 
Syntactical construct: TRY..ENDTRY 
DATA excp TYPE REF TO cx_sy_file_open...
SAP TechEd ‘07 
"– any statements 
CATCH cx_e1 ... cx_eN [ INTO excp1 ]. 
"– handler code for exceptions cx_e1 ..cx_eN 
CA...
SAP TechEd ‘07 
TRY. 
"– any statements 
CATCH cx_e1 ... cx_eN [ INTO excp1 ]. 
"– handler code for exceptions cx_e1 ..cx_...
SAP TechEd ‘07 
„ Superclasses can be used in CATCH clauses to catch all 
exceptions of any subtype 
„ Order of clauses is...
SAP TechEd ‘07 
Automatic Exception Propagation 
METHOD show. "IMPORTING a_page TYPE string 
METHOD retrieve. "IMPORTING a...
SAP TechEd ‘07 
How to Find the Right Exception Handler 
no 
yes 
88 
Exception 
occurred 
Inside 
protected 
area? 
Look ...
SAP TechEd ‘07 
How to Guarantee a Consistent State 
Problem 
„ Procedures are left premature 
„ Objects / application mig...
SAP TechEd ‘07 
dispatcher-show( a_page ). 
CATCH cx_page_not_found cx_misformed_url. 
 -- Error handling. 
METHOD show. I...
SAP TechEd ‘07 
CLEANUP clause is processed if and only if exception 
„ Has occurred 
„ Is not caught in current TRY – con...
SAP TechEd ‘07 
Principles of Exception Handling 
Exception Raising 
Catching Exceptions 
Declaration of Exceptions 
Defin...
SAP TechEd ‘07 
„ How do users of a procedure know which exceptions to expect? 
Solution 
„ Exceptions that are not handle...
SAP TechEd ‘07 
Declaration in subroutines (forms), function modules and 
methods 
... RAISING cx_e1 cx_e2 ... cx_eN 
Each...
SAP TechEd ‘07 
Exceptions in Procedure Declarations 
How to declare exceptions in class / function builder 
95 
© SAP AG ...
SAP TechEd ‘07 
Limitations of Static Checking (1) 
Some exceptions may occur anywhere, but are hard to be 
handled locall...
SAP TechEd ‘07 
Limitations of Static Checking (2) 
For some exceptions, users can ensure that they will not 
occur 
„ The...
SAP TechEd ‘07 
Three categories of exceptions 
CX_STATIC_CHECK CX_DYNAMIC_CHECK CX_NO_CHECK 
98 
Exception Class Hierarch...
SAP TechEd ‘07 
Can be used in RAISING clause 
99 
Exception Class Hierarchy 
Signature 
statically 
checked 
by compiler ...
SAP TechEd ‘07 
Principles of Exception Handling 
Exception Raising 
Catching Exceptions 
Declaration of Exceptions 
Defin...
SAP TechEd ‘07 
Exception Classes: Methods and Attributes 
Each exception class can define its own attributes 
„ Attribute...
SAP TechEd ‘07 
Attribute previous: 
„ Enables chaining of exceptions 
Example: undeclared exception leaves procedure 
„ E...
SAP TechEd ‘07 
„ Points to textual description of the exception 
Method get_text, get_longtext: 
„ Returns textual descri...
SAP TechEd ‘07 
104 
Exception Builder 
© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 
Substituted by 
attribute valu...
SAP TechEd ‘07 
They can be used to differentiate between related 
exceptions 
„ No need to define separate exception clas...
SAP TechEd ‘07 
Exercise 4 
106 
© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
SAP TechEd ‘07 
Principles of Exception Handling 
Exception Raising 
Catching Exceptions 
Declaration of Exceptions 
Defin...
SAP TechEd ‘07 
Motivation for Resumable Exceptions 
Situations where exception paradigm is difficult to use 
– error in s...
SAP TechEd ‘07 
Prerequisites for Resumable Exceptions 
„ Exception is raised as resumable 
„ Exception is propagated as r...
SAP TechEd ‘07 
Raising Resumable Exceptions 
Signaler of exception allows resumption with 
RAISE RESUMABLE EXCEPTION TYPE...
SAP TechEd ‘07 
Handling Resumable Exceptions 
Prerequisite for resumption: context is kept 
„ CATCH unwinds the stack 
„ ...
SAP TechEd ‘07 
Handler may resume execution 
„ Jump back to where the exception was raised (statement after RAISE) 
„ No ...
SAP TechEd ‘07 
CALL METHOD m1 … 
CATCH BEFORE UNWIND cx_some_excp INTO ex. 
IF ex-is_resumable = abap_true. 
… RESUME. 
M...
SAP TechEd ‘07 
Example without resumption 
CALL METHOD m1 … 
CATCH BEFORE UNWIND cx_some_excp INTO ex. 
METHOD m1. 
TRY. ...
SAP TechEd ‘07 
Declaring Resumable Exceptions 
„ How do users of a procedure know which of the expected exceptions 
may b...
SAP TechEd ‘07 
Exercise 5 
116 
© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
SAP TechEd ‘07 
Appendix 
117 
© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
SAP TechEd ‘07 
Appendix: MVC in Web Dynpro 
Appendix: ABAP Type Hierarchy 
118
SAP TechEd ‘07 
Web Dynpro Component Architecture 
SAP Web Dynpro uses principles of MVC paradigm 
Interface view 
119 
© ...
SAP TechEd ‘07 
120 
© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 
types 
data types object 
types 
elementary 
data...
SAP TechEd ‘07 
SAP Developer Network (SDN): www.sdn.sap.com 
Business Process Expert (BPX) Community: www.bpx.sap.com 
Î ...
SAP TechEd ‘07 
SDN Subscriptions Program 
The SDN Subscriptions Program introduces the SAP 
NetWeaver, Development Subscr...
SAP TechEd ‘07 
123 
Q  A 
© SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 
THANK YOU FOR YOUR 
ATTENTION ! 
QUESTIONS ...
SAP TechEd ‘07 
Please complete your session evaluation. 
Be courteous — deposit your trash, 
and do not take the handouts...
SAP TechEd ‘‘07 
SAP Certifications Related to SAP TechEd Topics 
Topic Exam Level Certificate Title Solution Basis 
ABAP ...
SAP TechEd ‘07 
Copyright 2007 SAP AG. All Rights Reserved 
No part of this publication may be reproduced or transmitted i...
Próximos SlideShares
Carregando em…5
×

Abap advanced

962 visualizações

Publicada em

vvvv

Publicada em: Educação

Abap advanced

  1. 1. SAP TechEd ‘07 CD350 Advanced ABAP Programming 1
  2. 2. SAP TechEd ‘07 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. 2 Disclaimer © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  3. 3. SAP TechEd ‘07 Development Architect, SAP AG 3 Contributing Speakers Frank Bertelsmeier Senior Developer, SAP AG Rolf Hammer © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  4. 4. SAP TechEd ‘07 As a result of this workshop, you will be able to: „ Utilize design aspects how to write reusable services in ABAP „ Make 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 4 Learning Objectives © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  5. 5. SAP TechEd ‘07 Advanced Programming Guidelines Generic Programming Exception Handling 5
  6. 6. SAP TechEd ‘07 How to Organize your Software? How to Accomplish Reuse? ABAP Programming Recommendations 6
  7. 7. SAP TechEd ‘07 Software Architecture Principles Defines software (like an ABAP application) to be decomposed and organized in more manageable parts (= components / modules / services) and how these interact. Goal: Increase quality, comprehensibility, 7 Software architecture Application Implementation (One or several ABAP programs) NW AS ABAP © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 reusability and maintainability. Architecture Principles Information hiding = Define modules as black boxes only showing relevant information 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 or changeabilty „ 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)
  8. 8. SAP TechEd ‘07 Assign the components of a software to different concerns or layers of abstraction (partioning) and reflect their interface interdependencies (behaviour). 8 Software-layer Architecture Layer architecture Layer 2 … NW AS ABAP © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 Layer Principles „ Hierarchical organization „ Each 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 Layer 1 Layer n
  9. 9. SAP TechEd ‘07 Example for Software-layer Architecture Application Services 9 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 Organize your application logic according classic Three-tiered architecture NW AS ABAP Non-ABAP UI Logic Persistence Presentation layer Application layer (Business logic) Persistence layer Screens, controls, flow logic, commands etc. Data repositories, transaction service
  10. 10. SAP TechEd ‘07 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 10 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 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 logic „ Is the basis for: – Using different data provider services (simulation of DB operations) – Controlled DB access, including additional services, e.g. caching, locking, transaction management „ Is 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
  11. 11. SAP TechEd ‘07 Model View Controller (MVC) MVC for decoupling presentation and application logic Generates the application data without caring how it will be displayed. Business Interaction Layer 11 Request Response © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 User Interaction Layer Binding Layer Visualizes the application data without caring how it was generated. Binds the user and business interaction layers together. All intermediate processing is performed here. Model View Controller „ Model-View-Controller (MVC) design paradigm originally invented by the Norwegian software designer Trygve Reenskaug (pronounced “TRIG-vuh RAINS-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.
  12. 12. SAP TechEd ‘07 Separation of Presentation Logic – MVC for Classic Dynpro GUI Status GUI Functions 12 Class Pool Local Classes lokale Klassen © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 Globale Daten Globale Daten Globale Daten Globale Daten Dynpro Screen Layout Dynpro Fields Global Data, Local Classes PBO PBO Module PAI PAI Module Function Group FUNCTION MODULES CALL SCREEN … Global Class lokale Klassen 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 dynpro instead 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.
  13. 13. SAP TechEd ‘07 Decoupling and Law of Demeter (LoD) Minimize coupling of components: Law of demeter Each component should only have limited knowledge about other components - “Only talk to your immediate friends” IMPORTING paramA TYPE REF TO classA. 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( ) ). 13 CLASS classDemeter DEFINITION. PUBLIC SECTION. METHODS doSomething PRIVATE SECTION. ENDMETHOD. ENDCLASS. © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 Methods of instances passed as parameter Methods of attributes of own class (association) Methods of own class Methods of locally created instances
  14. 14. SAP TechEd ‘07 How to Organize your Software? How to Accomplish Reuse? ABAP Programming Recommendations 14
  15. 15. SAP TechEd ‘07 Don’t repeat, use parts and knowledge of existing software „ Reuse increases efficiency in software development „ 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 15 What Means Reuse? – Saves costs, reduces effort – Reduces bugs, improves qualitiy © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 Requires initial investment, but quickly 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.
  16. 16. SAP TechEd ‘07 Good modularization is basis for reuse „ Identify modules: One self-contained concept / concern / aspect „ Consider 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 services „ which implements a well-defined functionality „ which have an orthogonal, concise interface „ which can be used independently of other components „ which are open for useful extensions „ which are intuitive to use (naming, behaviour) „ which are reliable (module tests) 16 How to Achieve Reuse? © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  17. 17. SAP TechEd ‘07 How to Organize your Software? How to Accomplish Reuse? ABAP Programming Recommendations 17
  18. 18. SAP TechEd ‘07 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 ABAP cleanup effective in ABAP Objects and Unicode-enabled programs 18 – Runtime Type Services (RTTS) – Advanced Exception Handling – Shared objects © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  19. 19. SAP TechEd ‘07 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 helper implementation „ Prefer instance methods rather than static ones (use singleton pattern instead) „ Use inhertiance only for „Is-a“ relations vs. delegates for „Has-a“ relations „ Separate 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 19 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  20. 20. SAP TechEd ‘07 Development Life Cycle System Analysis & Design Ensure quality and reliability by regularly testing your service „ Code Inspector – Don’t run into problems which can be detected by static code checks – Sophisticated code analysis for robustness, performance, security etc. – 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) 20 Development & Testing „ ABAP Unit © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 Testing Requirements Analysis Implementation Testing Maintainance But testing is ubiquitous!
  21. 21. SAP TechEd ‘07 Static Checks: Code Inspector 21 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 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 inspector transactions „ 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
  22. 22. SAP TechEd ‘07 ABAP Unit tests are implemented as local ABAP Objects classes in the ABAP program that contains the tested components. 1. Write a local class with the extension FOR TESTING „ Class Builder: Utilities → Test Classes → Generate 2. Write at least one method in this class with no parameters and 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) „ Class Builder: Class → Module Test „ ABAP Editor: Program → Execute → Module Test 22 ABAP Unit – Writing Tests extension FOR TESTING. 5. Execute the unit test © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 „ 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_assert „ Fixtures 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.
  23. 23. SAP TechEd ‘07 23 ABAP Unit – Result Display © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 „ 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.
  24. 24. SAP TechEd ‘07 ABAP Editor – Code Completion Code Completion provides easy access to services Code Completion „ Suggests 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 24 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  25. 25. SAP TechEd ‘07 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) 25 – CALL METHOD – CREATE OBJECT – RAISE EVENT – RAISE EXCEPTION TYPE – CALL FUNCTION – PERFORM „ Detailed Quick-Info © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  26. 26. SAP TechEd ‘07 ABAP Programming Guidelines – Summary Writing modern ABAP means: „ Keep your coding structured and modularized — always use ABAP „ Keep up the separation of concerns – model your applications strictly service-oriented, always disentangle the logics for presentation and application „ Keep your coding clean — don’t use language elements that are marked as obsolete, especially work only with Unicode enabled programs „ Keep 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 26 Objects appropriate tools © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  27. 27. SAP TechEd ‘07 Exercise 1 27 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  28. 28. SAP TechEd ‘07 Advanced Programming Guidelines Generic Programming Exception Handling 28
  29. 29. SAP TechEd ‘07 Basic Generic Concepts Dynamic Statements Dynamic Type Creation 29
  30. 30. SAP TechEd ‘07 Basics of Generic Programming Generic Programming „ Coding is able to deal with more generally typed data „ Technical 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 Services „ Usage of service is widened to (planned) variants „ Increased reuse range „ Abstraction necessary: Extract the core purpose and supply remainder otherwise „ Example: ALV 30 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 „ 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 Inspector Print contents of database table with user-supplied parameters – Name of database table – WHERE condition
  31. 31. SAP TechEd ‘07 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. ANY, DATA SIMPLE, NUMERIC INDEX TABLE HASHED TABLE 31 Generic Types © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 ANY TABLE SORTED TABLE STANDARD TABLE C, N, X, P CLIKE, CSEQUENCE, XSEQUENCE Fully generic (i.e. untyped) Partially generic Generic length Generic table kind and key
  32. 32. SAP TechEd ‘07 Generic Types Generic type specification used for „ Parameters METHOD foo_1 IMPORTING p1 TYPE any. ... ENDMETHOD. METHOD foo_2 IMPORTING p1 TYPE numeric. ... p1 = p1 * 2. ENDMETHOD. „ Field symbols <fs_any> TYPE any, <fs_c> TYPE c. "of any length dref_any TYPE REF TO DATA, dref_con TYPE REF TO structtype. "concrete type 32 FIELD-SYMBOLS: „ Data references DATA: © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  33. 33. SAP TechEd ‘07 Field Symbols Field symbols „ Aliases for existing data fields (or parts of them) „ Assigned at run time „ No copying of data, just referring to same memory „ Similar to parameters which are passed “Call-by-reference” „ Casting possible to obtain a specified technical view on the data text(20) TYPE c VALUE 'Hello world'. ASSIGN text TO <fs> CASTING [TYPE … | LIKE …] WRITE / <fs>. 33 DATA: FIELD-SYMBOLS: <fs> TYPE any. ASSIGN text TO <fs>. WRITE / <fs>. © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  34. 34. SAP TechEd ‘07 LargeField(10) TYPE C VALUE '1234567890', TypeName(7) TYPE C VALUE 'MY_TYPE', SomeType TYPE REF TO cl_abap_typedescr. <fs> TYPE my_type. ASSIGN LargeField TO <fs> CASTING. ASSIGN LargeField TO <fa> CASTING TYPE MY_TYPE. ASSIGN LargeField TO <fa> CASTING TYPE N. ... dynamically specified type 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>. 34 Casting Field Symbols TYPES: MY_TYPE(9) TYPE C. DATA: SmallField(5) TYPE C, FIELD-SYMBOLS: <fa> TYPE any, © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 Casting to … ... statically completely specified type ... generic type ... static field type …dynamic field type
  35. 35. SAP TechEd ‘07 Data references are pointers to data objects „ Using non-generic reference types DATA iref TYPE REF TO typename. „ Using fully-generic reference type DATA dref TYPE REF TO DATA. Reference types can also be used in classes, structure types etc. Typical uses for data references „ Save pointers to previously processed data „ Build generic containers for arbitrary data objects „ Create advanced data structures (like trees) 35 Data References © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  36. 36. SAP TechEd ‘07 Assigning a data reference variable GET REFERENCE OF DataObject INTO dref CREATE DATA dref TYPE | LIKE ... Access always requires dereferencing (->*, ->) Access to typed reference X = dref->*. "access the complete data object Y = dref->comp. "access component of a structure FIELD-SYMBOLS: <fs> TYPE any, 36 Usage of Data References Access to untyped reference © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 <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)
  37. 37. SAP TechEd ‘07 Dynamic Creation of Data Objects 37 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. © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 dref CREATE DATA dref TYPE struc. ASSIGN dref->* TO <str>. 36 ABC <str> <str>-a = 36. <str>-b = 'ABC'. CREATE DATA dref LIKE int. ASSIGN dref->* TO <int>. 5 <int> <int> = 5. tname = 'SFLIGHT'. CREATE DATA dref TYPE (tname). ASSIGN dref->* TO <f>. <f> SELECT SINGLE * FROM (tname) INTO <f>. 000 AA 0017
  38. 38. SAP TechEd ‘07 Basic Generic Concepts Dynamic Statements Dynamic Type Creation 38
  39. 39. SAP TechEd ‘07 Statements usually use arguments that refer to names of entities defined in the ABAP code or in a repository like the DDic. „ Static statement: STATEMENT … argument … SELECT * FROM SFLIGHTS INTO wa WHERE CARRID = 'LH'. SORT itab BY comp. Some ABAP statements can be supplied with coding for certain arguments dynamically. „ Dynamic statement: STATEMENT … (field) … dbname = 'SFLIGHTS'. SELECT * FROM (dbname) INTO wa WHERE CARRID = 'LH'. compname = 'COMP'. SORT itab BY (compname). „ To substitute the dynamic part (field) the content of field is evaluated at runtime. 39 Dynamic Statement © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  40. 40. SAP TechEd ‘07 Entities that statements may specify dynamically include „ Fields „ Types „ Structure components „ Forms, methods, functions, and programs, including parameters „ Statement subclauses Restrictions „ Value of dynamic part must be supplied in upper case „ No static type checks for dynamic statements „ Runtime error occurs if value of dynamic part is invalid 40 Dynamic Statement Parts © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  41. 41. SAP TechEd ‘07 Dynamic Field Specification Refer dynamically to a field or a database table „ ASSIGN (field) TO … „ SELECT … FROM (dbtab) … „ DELETE … FROM (dbtab) … „ MODIFY (dbtab) … „ UPDATE (dbtab) … „ WRITE … TO (field) „ WRITE (field) TO … 41 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 CONSTANTS: a TYPE i VALUE 1, b TYPE i VALUE 2. DATA: name(5) TYPE c. FIELD-SYMBOLS: <i> TYPE i. * Dynamic ASSIGN to a name = 'A'. ASSIGN (name) TO <i>. WRITE: <i>. "=1 * Dynamic ASSIGN to b name = 'B'. ASSIGN (name) TO <i>. WRITE: <i>. "=2
  42. 42. SAP TechEd ‘07 Dynamic Type Specification Refer dynamically to local types or data dictionary types „ ASSIGN ... CASTING TYPE (type) „ CREATE DATA ... TYPE (type) ... „ CREATE DATA ... TYPE TABLE OF (type) ... DATA dref TYPE REF TO data. FIELD-SYMBOLS <dobj> TYPE any. 42 PERFORM create USING dref 'SFLIGHT'. ASSIGN dref->* to <dobj>. © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 * create data object of type * given by tname FORM create USING dref TYPE REF TO data tname 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>.
  43. 43. SAP TechEd ‘07 Dynamic Component Specification Refer dynamically to structure components „ SORT ... BY (comp1) ... (compn) „ READ TABLE ... WITH KEY (k1) = v1 ... (kn) = vn „ DELETE ... COMPARING (comp1) ... (compn) „ MODIFY ... TRANSPORTING (comp1) ... (compn) „ ASSIGN COMPONENT (comp) OF STRUCTURE ... 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) = val2 BINARY SEARCH. Statements processing internal tables ignore empty parts 43 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  44. 44. SAP TechEd ‘07 Dynamic Clause Specification Include statement clauses dynamically with internal tables „ SELECT (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 table APPEND 'CARRID = ''LH'' AND' TO condtab. APPEND 'CITYTO = ''NEW YORK''' TO condtab. * database fetch with dynamic WHERE condition SELECT * FROM spfli INTO wa WHERE (condtab). WRITE: / wa-carrid, wa-connid, wa-cityfrom. 44 ENDSELECT. © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  45. 45. SAP TechEd ‘07 Exercise 2 45 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  46. 46. SAP TechEd ‘07 Basic Generic Concepts Dynamic Statements Dynamic Type Creation 46
  47. 47. SAP TechEd ‘07 Run Time Type Services (RTTS) 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 47 Dynamic Type Creation © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  48. 48. SAP TechEd ‘07 48 RTTS Class Hierarchy CL_ABAP_REFDESCR © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 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
  49. 49. SAP TechEd ‘07 Principles of Types in ABAP „ Are immutable „ Describe all properties of the type „ Can be used instead of type name Named types and elementary types are managed by the runtime system 49 Type is well-defined by its type object „ For every type there is a run time type object „ Every type object corresponds to a type Type object is instance of RTTS class Type objects © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 CL_ABAP_STRUCTDESCR name age TYPES: BEGIN OF struc, name TYPE string, age TYPE i, END OF struc. oo struc
  50. 50. SAP TechEd ‘07 DATA: strucType TYPE REF TO cl_abap_structdescr. structType ?= cl_abap_typedescr=>describe_by_name( 'SPFLI' ). DATA: dataType TYPE REF TO cl_abap_datadescr, dataType ?= cl_abap_typedescr=>describe_by_data( field ). DATA: elemType TYPE REF TO cl_abap_elemdescr. elemType = cl_abap_elemdescr=>get_i( ). elemType = cl_abap_elemdescr=>get_c( 20 ). 50 How to get a Type Object Get type object by type name Get type object froma data object field(5) TYPE c. Get elementary types © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 „ 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, you could 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 what you want.
  51. 51. SAP TechEd ‘07 Create a data object of a specific type 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. Casting of a field symbol using a type object 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. 51 Working with Type Objects © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 „ You can create a data object from a type object only, if the type is instantiatable, that means, if the type objects doesn‘t represent a fully or partly generic 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.
  52. 52. SAP TechEd ‘07 Principles of Dynamic Type Creation „ Transient (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 only „ Create new types based on existing ones 52 Dynamically created types are „ Structure types „ Table types „ Reference types Bottom-up approach © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  53. 53. SAP TechEd ‘07 Implicit vs. Explicit Type Creation „ Declarative approach „ Only for table and reference types CREATE DATA dref TYPE TABLE OF type. CREATE DATA dref TYPE REF TO type. „ Procedural approach „ Factory method CREATE( ) in RTTS classes structType = CL_ABAP_STRUCTDESCR=>create( compTab ). 53 Implicit type creation Explicit Type creation © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 „ A type is implicitely created during creation of a data object, if the type doesn‘t exist. This is comparable to the (static) definition of a data object without explicit 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 sorts of 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 by corresponding get_XXX( ) methods in CL_ABAP_ELEMDESCR. Consequently, CL_ABAP_ELEMDESCR has no factory method CREATE( ).
  54. 54. SAP TechEd ‘07 Limitations of Dynamically Created Types Every call of factory method CREATE( ) creates a new type Types cannot be destroyed „ Type object is garbage collected if there are no data objects of that type Reuse of dynamically created types via factory method GET( ) (since 7.1) „ Same signature as create „ Returns type object with same properties „ Creates type if not existing yet For GET( ) types are considered equal, if „ Table types have the same line type and same table properties „ Reference types have the same base type „ Structure types have the same component names and types 54 anymore © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  55. 55. SAP TechEd ‘07 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 Line type mandatory, other parameters optional CREATE_WITH_KEY( ) alternative factory for tables with multiple (secondary) keys 55 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  56. 56. SAP TechEd ‘07 Dynamic Creation of Table Types CLASS cl_abap_tabledescr DEFINITION ... p_line_type TYPE REF TO cl_abap_datadescr p_table_kind TYPE abap_tablekind 56 CLASS-METHODS create IMPORTING © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 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_std tablekind_sorted tablekind_hashed
  57. 57. SAP TechEd ‘07 Dynamic Creation of Table Types CLASS cl_abap_tabledescr DEFINITION ... p_line_type TYPE REF TO cl_abap_datadescr p_table_kind TYPE abap_tablekind 57 CLASS-METHODS create IMPORTING © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 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 keydefkind_default keydefkind_tableline keydefkind_user
  58. 58. SAP TechEd ‘07 Dynamic Creation of Table Types CLASS cl_abap_tabledescr DEFINITION ... p_line_type TYPE REF TO cl_abap_datadescr p_table_kind TYPE abap_tablekind 58 CLASS-METHODS create IMPORTING © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 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 for structured line types: name Alternatives keydefkind_default keydefkind_tableline keydefkind_user
  59. 59. SAP TechEd ‘07 Example of Dynamic Table Type Creation 59 CARRID CONNID DISTANCE ... © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 TYPES tableType TYPE SORTED TABLE OF spfli WITH UNIQUE KEY carrid connid. LH 0400 6.162 LH 0400 5.347 QF 0005 1.000 SQ 0866 1.625 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 = lineType p_table_kind = cl_abap_tabledescr=>tablekind_sorted p_unique = abap_true p_key = key ).
  60. 60. SAP TechEd ‘07 Example of Dynamic Table Type Creation CARRID CONNID DISTANCE ... DATA: lineType TYPE REF TO cl_abap_structdescr, tableType TYPE REF TO cl_abap_tabledescr, key TYPE abap_keydescr_tab. cl_abap_typedescr=>describe_by_name( 'SPFLI' ). APPEND 'CARRID' TO key. APPEND 'CONNID' TO key. tableType = cl_abap_tabledescr=>create( p_line_type = lineType p_table_kind = cl_abap_tabledescr=>tablekind_sorted p_unique = abap_true p_key = key ). 60 lineType ?= © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 CL_ABAP_STRUCTDESCR distance : oo spfli carrid connid oo lineType LH 0400 6.162 LH 0400 5.347 QF 0005 1.000 SQ 0866 1.625 TYPES tableType TYPE SORTED TABLE OF spfli WITH UNIQUE KEY carrid connid.
  61. 61. SAP TechEd ‘07 Example of Dynamic Table Type Creation CARRID CONNID DISTANCE ... DATA: lineType TYPE REF TO cl_abap_structdescr, tableType TYPE REF TO cl_abap_tabledescr, key TYPE abap_keydescr_tab. cl_abap_typedescr=>describe_by_name( 'SPFLI' ). APPEND 'CARRID' TO key. APPEND 'CONNID' TO key. tableType = cl_abap_tabledescr=>create( keytab p_line_type = lineType p_table_kind = cl_abap_tabledescr=>tablekind_sorted p_unique = abap_true p_key = key ). 61 lineType ?= © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 CL_ABAP_STRUCTDESCR distance : oo spfli carrid connid oo CARRID CONNID LH 0400 6.162 LH 0400 5.347 QF 0005 1.000 SQ 0866 1.625 TYPES tableType TYPE SORTED TABLE OF spfli WITH UNIQUE KEY carrid connid. lineType
  62. 62. SAP TechEd ‘07 Example of Dynamic Table Type Creation CARRID CONNID DISTANCE ... DATA: lineType TYPE REF TO cl_abap_structdescr, tableType TYPE REF TO cl_abap_tabledescr, key TYPE abap_keydescr_tab. cl_abap_typedescr=>describe_by_name( 'SPFLI' ). APPEND 'CARRID' TO key. APPEND 'CONNID' TO key. tableType = cl_abap_tabledescr=>create( keytab p_line_type = lineType p_table_kind = cl_abap_tabledescr=>tablekind_sorted p_unique = abap_true p_key = key ). 62 lineType ?= © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 CL_ABAP_STRUCTDESCR distance : oo spfli carrid connid oo tableType LH 0400 6.162 LH 0400 5.347 QF 0005 1.000 SQ 0866 1.625 TYPES tableType TYPE SORTED TABLE OF spfli WITH UNIQUE KEY carrid connid. CL_ABAP_TABLEDESCR line_type o key lineType CARRID CONNID
  63. 63. SAP TechEd ‘07 Dynamic Creation of Reference Types 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. Create a reference type from a base type „ Base type may be class, interface or data type Short cut for named base types „ Easier to use „ Much more efficient for object types if type description object not yet 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. 63 created CLASS-METHODS create_by_name © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 „ Note that, when having class A, CL_ABAP_TYPEDESCR=>describe_by_name( 'A' ) returns the class, not the reference type to that class. Compare that to static definition of object variables: 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 that saves you retrieving the type object of the base type first. It's also a huge performance improvement for references to classes and interfaces, as getting type objects for them is rather expensive.
  64. 64. SAP TechEd ‘07 Examples of Dynamic Reference Type Creation 64 123 i: CL_SOME_CLASS © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 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' ).
  65. 65. SAP TechEd ‘07 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' ). 65 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 CL_ABAP_ELEMDESCR i_type 123 i: CL_SOME_CLASS baseType
  66. 66. SAP TechEd ‘07 Examples of Dynamic Reference Type Creation 123 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' ). 66 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 CL_ABAP_REFDESCR refToIType referenced_type o i: CL_SOME_CLASS baseType CL_ABAP_ELEMDESCR i_type TYPES: refToIType TYPE REF TO i, refToSomeClass TYPE REF TO cl_some_class.
  67. 67. SAP TechEd ‘07 Examples of Dynamic Reference Type Creation CL_ABAP_REFDESCR referenced_type o refToSomeClass 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' ). 67 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 baseType cl_some_class 123 i: CL_SOME_CLASS CL_ABAP_REFDESCR refToIType referenced_type o CL_ABAP_ELEMDESCR i_type TYPES: refToIType TYPE REF TO i, refToSomeClass TYPE REF TO cl_some_class.
  68. 68. SAP TechEd ‘07 Dynamic Creation of Structured Types 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. Create a structured type from a component description table 68 „ component table mandatory „ strictness optional © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 ABAP Objects naming conventions enforced
  69. 69. SAP TechEd ‘07 Component Description Table NAME TYPE AS_INCLUDE SUFFIX TYPES: 69 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 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( ). „ 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 lines with the same name. The degree of restrictions is controlled by the parameter p_strict when creating the structure. By default it is set to the same set of rules that apply to the definition of structures in ABAP-OO. „ The type column contains the type of the respective component. The type is expressed by a type object, as can be accessed/created via the RTTS framework.
  70. 70. SAP TechEd ‘07 Component Description Table 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( ). 70 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 personType CL_ABAP_STRUCTDESCR component_table
  71. 71. SAP TechEd ‘07 Component Description Table comp_tab: NAME TYPE AS_INCLUDE SUFFIX TYPES: 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( ). 71 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 BEGIN OF personType, name TYPE string, age(3) TYPE n, END OF personType. CL_ABAP_STRUCTDESCR component_table NAME AGE personType
  72. 72. SAP TechEd ‘07 Example of Dynamic Structure Type Creation NAME TYPE AS_INCLUDE SUFFIX EMPLOYEE 72 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 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 ).
  73. 73. SAP TechEd ‘07 Example of Dynamic Structure Type Creation NAME TYPE AS_INCLUDE SUFFIX TYPES: 73 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 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 ).
  74. 74. SAP TechEd ‘07 Example of Dynamic Structure Type Creation NAME TYPE AS_INCLUDE SUFFIX TYPES: CL_ABAP_STRUCTDESCR component_table 74 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 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 ).
  75. 75. SAP TechEd ‘07 Exercise 3 75 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  76. 76. SAP TechEd ‘07 Advanced Programming Guidelines Generic Programming Exception Handling 76
  77. 77. SAP TechEd ‘07 Principles of Exception Handling Exception Raising Catching Exceptions Declaration of Exceptions Definition of Exception Classes Resumable Exceptions 77
  78. 78. SAP TechEd ‘07 Principles of Exception Handling 1/2 Look at software as a (layered) collection of services In an error situation, a service „ has only limited knowledge about the (global) application context „ is probably not able to take corrective measures Best way to deal with error situation „ Signal what went wrong, passing along additional information „ Pass flow of control to a suitable handler which is able to react to that particular situation „ Handler may decide to abort or continue Requirements „ Separation of normal coding from error handler coding „ Selective definition of handlers for certain errors „ Automatic abort of routine, that cannot provide promised service 78 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  79. 79. SAP TechEd ‘07 Principles of Exception Handling 2/2 Exception as an object of an exception class „ Attributes can store additional information „ Refinement through inheritance „ Grouping by using inheritance Raising an exception „ Creation of exception object „ Propagation 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 procedures „ Callers know about exceptions they have to deal with In principle comparable to Java, C++ 79 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  80. 80. SAP TechEd ‘07 Principles of Exception Handling Exception Raising Catching Exceptions Declaration of Exceptions Definition of Exception Classes Resumable Exceptions 80
  81. 81. SAP TechEd ‘07 Raising Class-Based Exceptions Raise exception with implicit object creation RAISE EXCEPTION TYPE cx_page_not_found EXPORTING page = 'http://www.sap.com/shop/'. Raise exception with explicit object creation or re-raise a caught exception DATA excp TYPE REF TO cx_page_not_found. CREATE OBJECT excp EXPORTING page = 'http://www.sap.com/shop/'. Exception raised by kernel (runtime exception) x = 1 / 0. "creates exception cx_sy_zerodivide Exception object contains additional information, e.g. page, explaining text and position where exception occurred. 81 RAISE EXCEPTION excp. © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  82. 82. SAP TechEd ‘07 Principles of Exception Handling Exception Raising Catching Exceptions Declaration of Exceptions Definition of Exception Classes Resumable Exceptions 82
  83. 83. SAP TechEd ‘07 Catching Class-Based Exceptions Syntactical construct: TRY..ENDTRY DATA excp TYPE REF TO cx_sy_file_open_mode. TRY. OPEN DATASET file FOR OUTPUT IN BINARY MODE. TRANSFER xbuffer TO file. CLOSE DATASET file. WRITE: 'Buffer successfully written'. CATCH cx_sy_file_open_mode INTO excp. WRITE: 'File', excp->filename, 'is not open'. CATCH cx_sy_file_access_error WRITE: 'Other file IO exception occurred'. Consists of „ Exactly one protected code area „ One or more exception handlers 83 ENDTRY. © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  84. 84. SAP TechEd ‘07 "– any statements CATCH cx_e1 ... cx_eN [ INTO excp1 ]. "– handler code for exceptions cx_e1 ..cx_eN CATCH cx_f1 ... Cx_fM [ INTO excp2 ]. "– handler code for exceptions cx_f1 ..cx_fM ... ENDTRY. Protected area „ All statements between TRY and first CATCH „ Only exceptions that occur in protected area can be handled Handler code is not protected „ But TRY constructs can be nested 84 Protected Area TRY. © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  85. 85. SAP TechEd ‘07 TRY. "– any statements CATCH cx_e1 ... cx_eN [ INTO excp1 ]. "– handler code for exceptions cx_e1 ..cx_eN CATCH cx_f1 ... cx_fN [ INTO excp2 ]. "– handler code for exceptions cx_f1 ..cx_fN ... ENDTRY. Exception handlers (CATCH clauses) „ Are checked from top to bottom „ Each can handle one or more exceptions Optional access to exception object by INTO clause 85 Exception Handlers © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  86. 86. SAP TechEd ‘07 „ 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 86 Grouping by Polymorphism © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 CX_PAGE_NOT_FOUND CX_SY_ARITHMETIC_ERROR CX_SY_ZERODIVIDE CX_SY_ARITHMETIC_OVERFLOW
  87. 87. SAP TechEd ‘07 Automatic Exception Propagation METHOD show. "IMPORTING a_page TYPE string METHOD retrieve. "IMPORTING a_page TYPE string 87 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 … RAISE EXCEPTION TYPE cx_page_not_found … ENDMETHOD. TRY. 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.
  88. 88. SAP TechEd ‘07 How to Find the Right Exception Handler no yes 88 Exception occurred Inside protected area? Look for handler in corresponding TRY-block Handler found? © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 TRY-block found? Go up call hierarchy and look for outer TRY-block yes no Runtime Error no Process handler code Go to end of handler's TRY-block yes
  89. 89. SAP TechEd ‘07 How to Guarantee a Consistent State Problem „ Procedures are left premature „ Objects / application might be in an inconsistent state „ Example: allocated resources Solution „ Introduction of (optional) CLEANUP clause – any statements CATCH cx_e1 ... cx_eN [ INTO excp1 ]. – handler code for exceptions cx_e1 ..cx_eN ... CLEANUP [ INTO excp ]. - optional 89 TRY. – statements ENDTRY. © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  90. 90. SAP TechEd ‘07 dispatcher-show( a_page ). CATCH cx_page_not_found cx_misformed_url. -- Error handling. METHOD show. IMPORTING a_page TYPE string TRY. METHOD show. IMPORTING a_page TYPE string TRY. METHOD show. IMPORTING a_page TYPE string TRY. METHOD show. IMPORTING a_page TYPE string retrieve(a_page). TRY. retrieve( a_page ). retrieve( a_page ). CATCH cx_some_exception. retrieve( a_page ). CATCH cx_some_exception. CATCH cx_some_exception. -- Error handling for some exception. -- Error handling for some exception. CATCH cx_some_exception. -- Error handling for some exception. CATCH cx_other_exception. -- Error handling for some exception. CATCH cx_other_exception. CATCH cx_other_exception. -- Error handling for other exception. -- Error handling for other exception. CATCH cx_other_exception. -- Error handling for other exception. -- Error handling for other exception. CLEANUP. -- Free internal resources. ENDTRY. ENDMETHOD. ENDTRY. ENDMETHOD. ENDTRY. ENDMETHOD. ENDTRY. ENDMETHOD. METHOD retrieve. IMPORTING a_page TYPE string … RAISE EXCEPTION TYPE cx_page_not_found … ENDMETHOD. 90 Example CLEANUP Clause TRY. ENDTRY. © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  91. 91. SAP TechEd ‘07 CLEANUP clause is processed if and only if exception „ Has 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 abnormally „ No use of RETURN, EXIT, CONTINUE ... to leave the clause „ Exceptions inside of the CLEANUP clause must be handled locally 91 CLEANUP Clause © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  92. 92. SAP TechEd ‘07 Principles of Exception Handling Exception Raising Catching Exceptions Declaration of Exceptions Definition of Exception Classes Resumable Exceptions 92
  93. 93. SAP TechEd ‘07 „ How do users of a procedure know which exceptions to expect? Solution „ Exceptions that are not handled inside of the procedure are part of the procedure's signature METHODS: show IMPORTING a_page TYPE string 93 Declaring Exceptions Problem © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 RAISING cx_page_not_found. Benefits „ Users have only to deal with exceptions mentioned in a procedure's signature „ Compiler can check if an exception is either handled inside of a procedure or declared to leave it
  94. 94. SAP TechEd ‘07 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 process „ At 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) 94 RAISING Clause © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  95. 95. SAP TechEd ‘07 Exceptions in Procedure Declarations How to declare exceptions in class / function builder 95 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 Use class-based exceptions
  96. 96. SAP TechEd ‘07 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 declarations „ Or 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 „ 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 96 compile time) © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  97. 97. SAP TechEd ‘07 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 „ Typical examples: parameter constraints (e.g. cx_sy_zerodivide, 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 handled „ Runtime system does check if the exception was declared if it tries to Consequence: if user was wrong (exception leaves procedure) an exception is thrown (cx_sy_no_handler) 97 beforehand cx_misformed_url) leave the procedure © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  98. 98. SAP TechEd ‘07 Three categories of exceptions CX_STATIC_CHECK CX_DYNAMIC_CHECK CX_NO_CHECK 98 Exception Class Hierarchy Signature statically checked by compiler and dynamically at runtime © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 Signature checked only at runtime CX_ROOT Not in signature, never checked All exceptions are derived from corresponding classes
  99. 99. SAP TechEd ‘07 Can be used in RAISING clause 99 Exception Class Hierarchy Signature statically checked by compiler and dynamically at runtime © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 Signature checked only at runtime CX_ROOT CX_STATIC_CHECK CX_DYNAMIC_CHECK CX_NO_CHECK Not in signature never checked
  100. 100. SAP TechEd ‘07 Principles of Exception Handling Exception Raising Catching Exceptions Declaration of Exceptions Definition of Exception Classes Resumable Exceptions 100
  101. 101. SAP TechEd ‘07 Exception Classes: Methods and Attributes Each exception class can define its own attributes „ Attributes can be of any type „ Are preferably read-only Methods inherited from cx_root returns position where exception has been raised 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 101 „ get_source_position: „ get_text, get_longtext: © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  102. 102. SAP TechEd ‘07 Attribute previous: „ Enables chaining of exceptions Example: undeclared exception leaves procedure „ Exception cx_sy_no_handler is raised 102 Chaining of Exceptions CX_SY_NO_HANDLER Classname CX_PAGE_NOT_FOUND Previous TCeXx_tPidAGE_NOT_FOUND Page http://www.sap.com/shop/ © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 Chaining can be employed explicitly RAISE EXCEPTION TYPE cx_some_exception EXPORTING previous = caught_exception.
  103. 103. SAP TechEd ‘07 „ Points to textual description of the exception Method get_text, get_longtext: „ Returns textual description of the exception „ Occurrences of ‘ATTRIBUTE' in text are substituted by attribute values CX_PAGE_NOT_FOUND Page http://www.sap.com/shop/ at URL PAGE' 103 Exception Texts Attribute textid: © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 'No document No doIcnuvmaelnitd aatc cUoRuLn th totfp :c/u/swtwowm.esra pM.iccohma/eslhop/ Textid
  104. 104. SAP TechEd ‘07 104 Exception Builder © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 Substituted by attribute value Default exception id has same name as exception class
  105. 105. SAP TechEd ‘07 They can be used to differentiate between related exceptions „ No need to define separate exception classes for slight variants „ Should be really related – all attributes have same meaning for all id's „ Handlers usually will not differentiate between id's Raise exception with different text RAISE EXCEPTION TYPE cx_sy_file_position textid = cx_sy_file_position=tell_error ... 105 Multiple Exception Texts EXPORTING © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  106. 106. SAP TechEd ‘07 Exercise 4 106 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  107. 107. SAP TechEd ‘07 Principles of Exception Handling Exception Raising Catching Exceptions Declaration of Exceptions Definition of Exception Classes Resumable Exceptions 107
  108. 108. SAP TechEd ‘07 Motivation for Resumable Exceptions Situations where exception paradigm is difficult to use – error in sub-task should not terminate complete processing – check mode should collect all errors „ Resumption after error correction – problem has been fixed, service sould continue (e.g. authority check) Solution: Resumable Exceptions „ No automatic termination of service – Technically: no unwinding of the stack „ Handler can decide whether to terminate service or to continue „ Service must be prepared for resumption „ Services based on services, so all levels must agree 108 „ Mass data processing „ Collecting errors © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  109. 109. SAP TechEd ‘07 Prerequisites for Resumable Exceptions „ Exception is raised as resumable „ Exception is propagated as resumable (in RAISING clause) „ Handler chooses resumption “Resumability” „ Is not a property of the exception class, but of a single exception object „ Can get lost if not propagated as resumable „ Can be checked by evaluation of attribute is_resumable 109 Resumption is possible if © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  110. 110. SAP TechEd ‘07 Raising Resumable Exceptions Signaler of exception allows resumption with RAISE RESUMABLE EXCEPTION TYPE cx [ EXPORTING ... ] RAISE RESUMABLE EXCEPTION excp_obj Signaler must be prepared that statement might return (dependent of the handler) Be extremely careful with no-check exceptions 110 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  111. 111. SAP TechEd ‘07 Handling Resumable Exceptions Prerequisite for resumption: context is kept „ CATCH unwinds the stack „ CLEANUP blocks get processed New CATCH clause CATCH BEFORE UNWIND cx_1 ... cx_n [ INTO excp ] Properties „ Used in the same way as simple CATCH clauses „ Same semantics, however, context is kept „ Unwinding of stack is deferred until handler is finished „ CLEANUPs are processed when unwinding the stack 111 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  112. 112. SAP TechEd ‘07 Handler may resume execution „ Jump back to where the exception was raised (statement after RAISE) „ No unwinding of the stack „ CLEANUP blocks between signaler and handler are not processed Statement RESUME „ Only allowed in CATCH BEFORE UNWIND block „ Exception must be resumable, else runtime error 112 Resumption Prerequisites CX_SY_ILLEGAL_HANDLER © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  113. 113. SAP TechEd ‘07 CALL METHOD m1 … CATCH BEFORE UNWIND cx_some_excp INTO ex. IF ex-is_resumable = abap_true. … RESUME. METHOD m1. TRY. CALL METHOD m2 … CATCH cx_other_exception. -- Error handling for other exception. CLEANUP. – fixing things up ENDTRY. ENDMETHOD. METHOD m2. … RAISE RESUMABLE EXCEPTION TYPE cx_some_excp … … ENDMETHOD. 113 Example with resumption TRY. ENDIF. ENDTRY. © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  114. 114. SAP TechEd ‘07 Example without resumption CALL METHOD m1 … CATCH BEFORE UNWIND cx_some_excp INTO ex. METHOD m1. TRY. CALL METHOD m2 … CATCH cx_other_exception. -- Error handling for other exception. CLEANUP. – fixing things up ENDTRY. ENDMETHOD. METHOD m2. … RAISE RESUMABLE EXCEPTION TYPE cx_some_excp … … ENDMETHOD. 114 TRY. … ENDTRY. … © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  115. 115. SAP TechEd ‘07 Declaring Resumable Exceptions „ How do users of a procedure know which of the expected exceptions may be resumable? Solution „ “Resumability” must be declared in procedures signature ... RAISING cx_e1 | RESUMABLE (cx_e1) ... „ Clause used for methods, function modules, forms „ RESUMABLE(cx) means: cx may be resumable, it doesn’t need to „ Controls 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 resumable „ Once the property is lost, it cannot be reestablished 115 Problem © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  116. 116. SAP TechEd ‘07 Exercise 5 116 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  117. 117. SAP TechEd ‘07 Appendix 117 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  118. 118. SAP TechEd ‘07 Appendix: MVC in Web Dynpro Appendix: ABAP Type Hierarchy 118
  119. 119. SAP TechEd ‘07 Web Dynpro Component Architecture SAP Web Dynpro uses principles of MVC paradigm Interface view 119 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 Business Logic (Models) Component Controller Model 1 Model 2 Contains Usage declarations Usage declarations W e b D y n p r o C o m p o n e n t Components Custom Controller Component Interface Interface Controller Interface view Window Window Controller View Layout View Controller M M M M M „ 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 paradigm SAP 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.
  120. 120. SAP TechEd ‘07 120 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 types data types object types elementary data types complex classes interfaces data types structure types table types reference types fixed length variable length data reference types object reference types ABAP Type Hierarchy
  121. 121. SAP TechEd ‘07 SAP Developer Network (SDN): www.sdn.sap.com Business Process Expert (BPX) Community: www.bpx.sap.com Î Related SAP Education and Certification Opportunities http://www.sap.com/education/ Î Related Workshops/Lectures at SAP TechEd 2007 CD256, Efficient Database Programming, Hands-on 2h CD354, Advanced Internal Table Programming Using Secondary Keys, CD252, ABAP Troubleshooting, Hands-on 4h CD253, ABAP Workbench Power Usage, Hands-on 2h CD250, ABAP and XML, Hands-on 4h CD200, News in ABAP – Concepts to Further Increase the Power of ABAP Development, Lecture 2h 121 Further Information Î SAP Public Web: Hands-on 2h © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  122. 122. SAP TechEd ‘07 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 updates „ Development license for SAP NetWeaver to evaluate, develop and test „ Standard software maintenance „ Online sessions from SAP TechEd „ Access to SAP Enterprise Services Workplace for testing „ Premium 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/devsub Visit us at the Community Clubhouse, show us you are a subscriber, and get a gift! 122 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350
  123. 123. SAP TechEd ‘07 123 Q A © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 THANK YOU FOR YOUR ATTENTION ! QUESTIONS – SUGGESTIONS – DISCUSSION
  124. 124. SAP TechEd ‘07 Please complete your session evaluation. Be courteous — deposit your trash, and do not take the handouts for the following session. 124 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350 Feedback Thank You !
  125. 125. SAP TechEd ‘‘07 SAP Certifications Related to SAP TechEd Topics Topic Exam Level Certificate Title Solution Basis ABAP Professional SAP Certified Development Professional - ABAP System Interfaces with 125 SAP NetWeaver 7.0 © SAP AG 2007, SAP TechEd ’07 / Session ID / 125 SAP 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
  126. 126. SAP TechEd ‘07 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. 126 © SAP AG 2007, SAP TechEd ’07 / Session ID / CD350

×