You are on page 1of 136

COMP273

Test-Driven and Bulletproof ABAP Development

Stefan Bresch, SAP AG NW F ABAP Thomas Ritter, SAP AG NW F ABAP

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.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 2

Agenda (Warm Up)

Everything that can possibly go wrong will go wrong (Murphys Law)

SAP 2008 / SAP TechEd 08 / <COMP273> Page 3

Agenda

1. Static checks
1.1. Code Inspector

2. Dynamic tests
2.1. Test Driven Development with ABAP Unit 2.2. Coverage Analyzer 3.3. ABAP Unit Browser

3. Robust code
3.1. Exceptions 3.2. Asserts

SAP 2008 / SAP TechEd 08 / <COMP273> Page 4

Static Checks: Code Inspection From The ABAP Editor


ABAP Editor Code inspection from SE38:
The Code Inspector executes a default test set for a chosen program. The default tests also contain the Extended Program Check (SLIN).

Code inspector is available with WEB AS 6.10


for R/3 >= 46C a transport is available -> note 543359
SAP 2008 / SAP TechEd 08 / <COMP273> Page 5

DEMO
SAP 2008 / SAP TechEd 08 / <COMP273> Page 6

Static Checks: Code Inspector Exercise

Exercise 1:
Use the code inspector to run the extended program check or syntax check for all our test programs. They start all with ZTSTECHED*

SAP 2008 / SAP TechEd 08 / <COMP273> Page 7

Agenda

1. Static tests
1.1. Code Inspector

2. Dynamic tests
2.1. Test Driven Development with ABAP Unit 2.2. Coverage Analyzer 3.3. ABAP Unit Browser

3. Robust code
3.1. Exceptions 3.2. Asserts

SAP 2008 / SAP TechEd 08 / <COMP273> Page 8

Introduction Unit Tests I

What are Unit Tests good for?


There is a gap between static and integration tests. Static checks cannot detect problems that occur only at runtime. Static checks cannot test if a function, form or method works as designed. Integration tests are too expensive to use for detecting errors on unit level. Unit tests allow you to execute a single modularization unit (method, form, function module) of a program under well-defined test conditions and to inspect and verify the behavior. A developer runs his unit tests every time he changes his code (regression tests) The first popular testframework was SUnit for Smalltalk developed by Kent Beck. Now, there are xUnit frameworks for nearly every programming language.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 9

Introduction Unit Tests II

Benefits
A developer runs his unit tests every time he changes his code (regression tests). Thereby defects are detected very early in the development process and can be fixed easily. A well written unit tests tells the developer exactly what is wrong and where the error is located. Therefore developers use the debugger less often for locating errors. Software grows over time therefore it is important to keep the code clean and agile. Extensive unit tests allow developers to reach this goal since they make refactorings possible which in return improves maintainability. Unit tests specify exactly how a piece of software should behave in a given scenario. Often unit tests serve as great examples how a certain piece of code should work, it therefore serves as an excellent technical documentation.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 10

Introduction ABAP Unit I

ABAP Unit is the official xUnit testing framework for ABAP. Its most remarkable features are:
1. 2. 3.

Tightly integrated into the programming language Production code and unit test code are bundled and transported together Test code cannot be executed in a production system.

ABAP Unit is available with NetWeaver 04.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 11

Introduction ABAP Unit II

ABAP Unit tests are usually implemented as local ABAP Objects classes in the main program that contains the tested modularization units.
Example test class definition:

CLASS ltcl_flight DEFINITION FOR TESTING RISK LEVEL HARMLESS DURATION SHORT. PRIVATE SECTION. METHODS: test_create_flight FOR TESTING. ENDCLASS.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 12

ABAP Unit For testing

For testing: used to mark classes as test classes and methods as test methods. Define class as test class

CLASS ltcl_flight DEFINITION FOR TESTING RISK LEVEL HARMLESS DURATION SHORT. PRIVATE SECTION. METHODS: test_create_flight FOR TESTING. ENDCLASS. Define method as test method

SAP 2008 / SAP TechEd 08 / <COMP273> Page 13

ABAP Unit Risk Level

Risk level: used to define the risk level of the test class dangerous, critical.

harmless,

Define risk level

CLASS ltcl_flight DEFINITION FOR TESTING RISK LEVEL HARMLESS DURATION SHORT. PRIVATE SECTION. METHODS: test_create_flight FOR TESTING. ENDCLASS.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 14

ABAP Unit Duration

Duration: used to define the expected runtime duration of all test methods short, medium, long. Define duration

CLASS ltcl_flight DEFINITION FOR TESTING RISK LEVEL HARMLESS DURATION SHORT. PRIVATE SECTION. METHODS: test_create_flight FOR TESTING. ENDCLASS.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 15

ABAP Unit System Configuration

Profile parameter: abap/test_generation

Transaction: SAUNIT_CLIENT_SETUP

SAP 2008 / SAP TechEd 08 / <COMP273> Page 16

ABAP Unit Assert Methods

Assert methods:
used to determine whether a test is successful or not the utility class cl_aunit_assert offers various methods e.g. assert_equals(), assert_bound(), Implement your own assert methods by using the method fail() all assert statements allow you to add a message via the parameter (msg) which will be displayed in the UI

Example: METHOD test_create_flight. DATA: flight TYPE REF TO cl_flight. CREATE OBJECT flight EXPORTING flight_id = LX34. cl_aunit_assert=>assert_bound( flight ). ENDMETHOD.
SAP 2008 / SAP TechEd 08 / <COMP273> Page 17

ABAP Unit Execute Tests

Start unit tests from within the SE80 or execute a row of tests by using the code inspector.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 18

ABAP Unit Result Display

SAP 2008 / SAP TechEd 08 / <COMP273> Page 19

DEMO
SAP 2008 / SAP TechEd 08 / <COMP273> Page 20

Dynamic Tests: ABAP Unit Exercise


Exercise 2:
Open the transaction SE80. Create a new report with the name ZTBEXERCISE2_<counter>. Create your first local test class by using the following template:
class ltcl_calculator_tests definition for testing duration short risk level harmless. private section. methods: divide_successful for testing. endclass. class ltcl_calculator_tests implementation. method divide_successful. endmethod. endclass.

Add a method DIVIDE to the local test class which receives two integer numbers as parameters, divides them and returns the result. The definition of the method looks like this: DIVIDE importing PARAM1 type i PARAM2 type i returning value(result) type i. Write a test which checks the result of the DIVIDE method. Use the static method CL_AUNIT_ASSERT=>ASSERT_EQUALS() for checking whether your test is successful or not. Execute your test by using the menu Program Test UnitTest or use the keyboard shortcut: Shift + Strg + F10. Get a feeling for the result display by causing your unit test to fail. Once you are finished try to add more tests. What happens if you try to divide a number by zero?
SAP 2008 / SAP TechEd 08 / <COMP273> Page 21

ABAP Unit Test Creation

Usual workflow when implementing a unit test:


1. Write the necessary code to set up the environment in which the test runs (Fixtures are defined by a naming convention, i.e. the methods setup, teardown and class_setup and class_teardown, respectively). 2. Implement the test in a method defined as for testing. Use the helper methods offered by the class cl_aunit_assert to check whether the code under test behaved in the way you expected it to behave. 3. Write the necessary code to tear down the environment. It is important that tests are running in complete isolation.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 22

ABAP Unit Test Execution

ABAP Unit test execution flow:


Setup for all tests class_setup() Setup for each test method Execute test method Teardown for each test method Teardown for all tests class_teardown()

setup()

test method

teardown()

SAP 2008 / SAP TechEd 08 / <COMP273> Page 23

ABAP Unit How to Define Fixture Methods

Example test class: CLASS ltcl_flight DEFINITION FOR TESTING RISK LEVEL HARMLESS DURATION SHORT. PRIVATE SECTION. CLASS-METHODS: class_setup, class_teardown. METHODS: setup, teardown. ENDCLASS.

Define fixture methods

SAP 2008 / SAP TechEd 08 / <COMP273> Page 24

Test Driven Development - Motivation

Common problems with the classic unit testing approach


Tests are written too late or not at all The production code is not testable Test coverage is low

SAP 2008 / SAP TechEd 08 / <COMP273> Page 25

Test Driven Development - Motivation

One solution:

Write the unit tests before the production code!

SAP 2008 / SAP TechEd 08 / <COMP273> Page 26

Test Driven Development - Process

Write test

Make it compile

Test fails

Make the test pass

Refactor
SAP 2008 / SAP TechEd 08 / <COMP273> Page 27

DEMO
SAP 2008 / SAP TechEd 08 / <COMP273> Page 28

Test Driven Development - Advantages

Test Driven Development can help you to:


improve the test coverage of your code by forcing you not to write any production code without a failing test. improve the design of your code by forcing you to design the API before implementing it. Helps you to design highly decoupled and thereby reusable code. make your code more flexible

SAP 2008 / SAP TechEd 08 / <COMP273> Page 29

Dynamic Tests: ABAP Unit Exercise

Exercise 3:
Open the transaction SE80. Create a new report ZTBEXERCISE3_<counter>. Create a new test class with the name LTCL_STACK_TESTS. Add a private attribute to the test class ZCL_STACK. data: stack type ref to

Implement the SETUP method which instantiates the stack attribute. Write a test for the POP and PUSH method of the stack class. Use the method ASSERT_EQUALS to make sure that the right results get returned. What happens if you call POP on an empty stack? Write a test for the method SIZE. Suggestion: One developer writes the test the other developer writes the implementation which passes the test
SAP 2008 / SAP TechEd 08 / <COMP273> Page 30

ABAP Unit Testability

What affects testability? (James Bach)


Controllability: You can only test what you can control. If the code under test interacts with a method which has a non-deterministic behavior writing a test is not possible. Observability: You can only test what you can see If its not possible to query and check system states which get changed by the code under test then it is hard to test. Availability: You can only test what you have access to Private methods cannot be tested easily however ABAP Objects friends feature offers a solution. Simplicity: The simpler, the easier its too test Long methods are usually hard to test because they are responsible for handling too many different things.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 31

ABAP Unit Testability

Best practices for testability:


clear separation between persistence, application, and UI coding object oriented programming. Use classes and interfaces to clearly define modules and to keep your code flexible simple clearly structured code. Short and precise methods. Every class, method should ideally have only one purpose

SAP 2008 / SAP TechEd 08 / <COMP273> Page 32

Agenda

1. Static tests
1.1. Code Inspector

2. Dynamic tests
2.1. Test Driven Development with ABAP Unit 2.2. Coverage Analyzer 3.3. ABAP Unit Browser

3. Robust code
3.1. Exceptions 3.2. Asserts

SAP 2008 / SAP TechEd 08 / <COMP273> Page 33

Coverage Analyzer

The Coverage Analyzer is a tool for monitoring the system-wide execution of ABAP programs. You can
monitor which programs and even which modules of a program were covered by a test find program parts or complete programs which are never used and may be obsolete. find program parts that are executed very often and may benefit from code optimization

Coverage Analyzer is available with WEB AS 6.10

SAP 2008 / SAP TechEd 08 / <COMP273> Page 34

Coverage Analyzer
SAP Easy Access

/nscov /nscov

Make sure that the coverage analyzer is running properly on your server before testing!
SAP 2008 / SAP TechEd 08 / <COMP273> Page 35

Coverage Analyzer Global View (QM)

SAP 2008 / SAP TechEd 08 / <COMP273> Page 36

Coverage Analyzer Detail View

Check which modularization units of your programs were executed (covered) during a test.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 37

DEMO
SAP 2008 / SAP TechEd 08 / <COMP273> Page 38

Agenda

1. Static tests
1.1. Code Inspector

2. Dynamic tests
2.1. Test Driven Development with ABAP Unit 2.2. Coverage Analyzer 3.3. ABAP Unit Browser

3. Robust code
3.1. Exceptions 3.2. Asserts

SAP 2008 / SAP TechEd 08 / <COMP273> Page 39

ABAP Unit Browser - Introduction

The ABAP Unit Browser is a tool for executing a set of unit tests. It allows to monitor the code coverage which unit tests produce.

ABAP Unit Browser is available with SAP NetWeaver 7.1


SAP 2008 / SAP TechEd 08 / <COMP273> Page 40

ABAP Unit Browser Create new favorite

1. Create a new favorite

SAP 2008 / SAP TechEd 08 / <COMP273> Page 41

ABAP Unit Browser Add Test Classes

2. Add test classes to the favorite

SAP 2008 / SAP TechEd 08 / <COMP273> Page 42

ABAP Unit Browser Configure Execution Options


3. Add coverage measurement

SAP 2008 / SAP TechEd 08 / <COMP273> Page 43

ABAP Unit Browser Execute Favorite

4. Execute tests

SAP 2008 / SAP TechEd 08 / <COMP273> Page 44

ABAP Unit Browser Analyze Results

5. Analyze results

SAP 2008 / SAP TechEd 08 / <COMP273> Page 45

ABAP Unit Browser Exercise

Exercise 4:
Open the transaction SE80. Select the ABAP Unit Browser (If the tool is not display in the workbench add it via the menu: Utilities Settings Under tab Workbench (General) tick the checkbox ABAP Unit Test Browser). Select Favorite in the dropdownlist and enter your username in the inputfield. Create a new favorite. Add the reports created during exercise 2 and 3 to the favorite. Tick the checkbox With Coverage Measurement under extended measurement. Execute the unit tests. Analyze the code coverage which your test methods produce. Optional: Execute your tests by using the Code Inspector.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 46

Agenda

1. Static tests
1.1. Code Inspector

2. Dynamic tests
2.1. Test Driven Development with ABAP Unit 2.2. Coverage Analyzer 3.3. ABAP Unit Browser

3. Robust code
3.1. Exceptions 3.2. Asserts

SAP 2008 / SAP TechEd 08 / <COMP273> Page 47

Motivation
Software development and operation is intrinsically prone to errors in many ways
Internal errors may arise from wrong implementations and improper usage of underlying services. When interacting with external resources (like the user, system memory or disk storage), errors can occur due to invalid input or unexpected resource limitations. The ABAP language and infrastructure offers different ways for handling these kinds of errors, both for recoverable ( exceptions, messages) and non-recoverable errors ( assertions).

SAP 2008 / SAP TechEd 08 / <COMP273> Page 48

Available Since
Exceptions
Class-Based Exceptions: SAP_BASIS 610 (SAP WebAS 610) with T100-texts: SAP_BASIS 6.40 (SAP NetWeaver 04, mySAP ERP 2004, CRM 4.0, ) Classical Exceptions: prior to Release 4.0 Catchable Runtime Errors: Release 4.0

SAP 2008 / SAP TechEd 08 / <COMP273> Page 49

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

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 ( automatic propagation along call chain)

SAP 2008 / SAP TechEd 08 / <COMP273> Page 50

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++

SAP 2008 / SAP TechEd 08 / <COMP273> Page 51

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/'. RAISE EXCEPTION excp.

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.
SAP 2008 / SAP TechEd 08 / <COMP273> Page 52

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'. ENDTRY.

Consists of
Exactly one protected code area One or more exception handlers
SAP 2008 / SAP TechEd 08 / <COMP273> Page 53

Protected Area

TRY. " 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

SAP 2008 / SAP TechEd 08 / <COMP273> Page 54

Exception Handlers

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

SAP 2008 / SAP TechEd 08 / <COMP273> Page 55

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_SY_ARITHMETIC_ERROR CX_PAGE_NOT_FOUND CX_SY_ZERODIVIDE CX_SY_ARITHMETIC_OVERFLOW

SAP 2008 / SAP TechEd 08 / <COMP273> Page 56

Exceptions Exercise
Exercise 5:
Open the transaction SE80. Create a new report ZTBEXERCISE5_<counter>. Create a new test class with the name LTCL_EXCEPTIONS_TESTS. Create a new test method with the name RAISE_EXCEPTION. Provoke the exception CX_SY_ZERODIVIDE by trying to divide a number by zero. Have a look at how ABAP Unit automatically catches exceptions. Now, write a test which makes sure that a) the system throws an exception when you try to divide a number by zero b) the system throws the exception CX_SY_ZERODIVIDE. One hint the method CL_AUNIT_ASSERT=>FAIL() should be used in the test method. Use the optional into clause to save the exception object into a variable. Use the debugger to see how the code gets executed.
SAP 2008 / SAP TechEd 08 / <COMP273> Page 57

Automatic Exception Propagation

TRY. dispatcher->show( a_page ). " -- More normal coding CATCH cx_page_not_found cx_misformed_url. " -- Error handling. ENDTRY. METHOD show. "IMPORTING a_page TYPE string 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. METHOD retrieve. "IMPORTING a_page TYPE string RAISE EXCEPTION TYPE cx_page_not_found ENDMETHOD.
SAP 2008 / SAP TechEd 08 / <COMP273> Page 58

How to Find the Right Exception Handler

Exception occurred

Inside protected area? yes Look for handler in corresponding TRY-block

no

yes

TRY-block found?

no

Runtime Error

Handler found? yes Process handler code


SAP 2008 / SAP TechEd 08 / <COMP273> Page 59

no

Go up call hierarchy and look for outer TRY-block

Go to end of handler's TRY-block

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 TRY. " any statements CATCH cx_e1 ... cx_eN [ INTO excp1 ]. " handler code for exceptions cx_e1 ..cx_eN ... CLEANUP [ INTO excp ]. "- optional " statements ENDTRY.
SAP 2008 / SAP TechEd 08 / <COMP273> Page 60

Example CLEANUP Clause


TRY. dispatcher->show( a_page ). CATCH cx_page_not_found cx_misformed_url. " -- Error handling. ENDTRY. METHOD show. "IMPORTING a_page TYPE string METHOD show. "IMPORTING a_page TYPE string METHOD show. "IMPORTING a_page TYPE string TRY. METHOD show. "IMPORTING a_page TYPE string TRY. TRY. 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. some exception. " -- Error handling for CATCH cx_some_exception. some exception. " -- Error handling for " -- Error handling for CATCH cx_other_exception. some exception. " -- Error handling for CATCH cx_other_exception. some exception. CATCH cx_other_exception. other exception. " -- Error handling for CATCH cx_other_exception. other exception. " -- Error handling for " -- Error handling for other exception. CLEANUP. " -- Error handling for other exception. " -ENDTRY. Free internal resources. ENDTRY. ENDMETHOD. ENDTRY. ENDMETHOD. ENDTRY. ENDMETHOD. ENDMETHOD. METHOD retrieve. "IMPORTING a_page TYPE string RAISE EXCEPTION TYPE cx_page_not_found ENDMETHOD.
SAP 2008 / SAP TechEd 08 / <COMP273> Page 61

CLEANUP Clause
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

SAP 2008 / SAP TechEd 08 / <COMP273> Page 62

Declaring Exceptions
Problem
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 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

SAP 2008 / SAP TechEd 08 / <COMP273> Page 63

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 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)

SAP 2008 / SAP TechEd 08 / <COMP273> Page 64

Exceptions in Procedure Declarations


How to declare exceptions in class / function builder

Use class-based exceptions

SAP 2008 / SAP TechEd 08 / <COMP273> Page 65

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 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
SAP 2008 / SAP TechEd 08 / <COMP273> Page 66

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 beforehand Typical 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 handled Runtime 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)
SAP 2008 / SAP TechEd 08 / <COMP273> Page 67

Exception Class Hierarchy


Three categories of exceptions
All exceptions are derived from corresponding classes

CX_ROOT

CX_STATIC_CHECK

CX_DYNAMIC_CHECK

CX_NO_CHECK

Signature statically checked by compiler and dynamically at runtime


SAP 2008 / SAP TechEd 08 / <COMP273> Page 68

Signature checked only at runtime

Not in signature, never checked

Exception Class Hierarchy


Can be used in RAISING clause

CX_ROOT

CX_STATIC_CHECK

CX_DYNAMIC_CHECK

CX_NO_CHECK

Signature statically checked by compiler and dynamically at runtime


SAP 2008 / SAP TechEd 08 / <COMP273> Page 69

Signature checked only at runtime

Not in signature never checked

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


get_source_position: returns position where exception has been raised get_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

SAP 2008 / SAP TechEd 08 / <COMP273> Page 70

Chaining of Exceptions
Attribute previous:
Enables chaining of exceptions

Example: undeclared exception leaves procedure


Exception cx_sy_no_handler is raised

CX_SY_NO_HANDLER Classname Previous


CX_PAGE_NOT_FOUND

Chaining can be employed explicitly


RAISE EXCEPTION TYPE cx_some_exception EXPORTING previous = caught_exception.

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

SAP 2008 / SAP TechEd 08 / <COMP273> Page 71

Exception Texts
Attribute textid:
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 Textid Page http://www.sap.com/shop/ 'No document at URL &PAGE&'

No document at URL http://www.sap.com/shop/

SAP 2008 / SAP TechEd 08 / <COMP273> Page 72

DEMO
SAP 2008 / SAP TechEd 08 / <COMP273> Page 73

Exception Builder

Default exception id has same name as exception class

Substituted by attribute value

SAP 2008 / SAP TechEd 08 / <COMP273> Page 74

Multiple Exception Texts


They can be used to differentiate between related exceptions
No need to define separate exception classes for sflight 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_aab_persistence EXPORTING textid = cx_aab_persistence=>cx_aab_...__flush_fail
SAP 2008 / SAP TechEd 08 / <COMP273> Page 75

Exception Text Repository


Online Text Repository (OTR)
Texts up to 255 characters supported Use of &ATTRIBUTE& in text for substitution Should not be used for exceptions with text in user interface

Messages (T100) available with SAP_BASIS 640


Texts no longer than 72 characters Only 4 parameters (&1 ... &4) in text for substitution, definition of mapping necessary (parameter attribute name) Can be directly used for user interface (MESSAGE) Technical: Exception class implements IF_T100_MESSAGE Attribute for text is IF_T100_MESSAGE~t100key, (contains message class, message number and the parameter mapping), but parameter in exception constructor is still called textid

SAP 2008 / SAP TechEd 08 / <COMP273> Page 76

Exceptions Based on Message Class

SAP 2008 / SAP TechEd 08 / <COMP273> Page 77

Local Exception Classes 1/2


Local exception classes can be defined
In the most simple case just inherit from CX_STATIC_CHECK, CX_DYNAMIC_CHECK or CX_NO_CHECK (or any already existing exception class) Define a constructor if you want to pass values to attributes Without specifying attribute for text you will get a default text

Local exceptions might be useful


during the development phase or for prototyping in the implementation part of a software layer

Local exceptions should normally be handled locally in a software layer

SAP 2008 / SAP TechEd 08 / <COMP273> Page 78

Local Exception Classes 2/2


Defining a text in local classes is quite tricky
Define constant for each exception id Constant refers to textual description (OTR key or T100 key) In constructor set attribute for exception text accordingly

OTR-Texts
For each exception id one constant of type SOTR_CONC Name is name of exception id, value is respective OTR GUID

T100-Texts
Implement IF_T100_MESSAGE For each exception id one constant of type SCX_T100KEY Values define msgid, msgno and parameter mapping

SAP 2008 / SAP TechEd 08 / <COMP273> Page 79

Exceptions Within the Debugger

Show exception object

Display exception position

SAP 2008 / SAP TechEd 08 / <COMP273> Page 80

Exceptions Within the Debugger

SAP 2008 / SAP TechEd 08 / <COMP273> Page 81

Exceptions Within the Debugger


You can tell the debugger to stop on certain exceptions

Condition is valid for subclasses too to stop on every exception, set breakpoint at CX_ROOT
SAP 2008 / SAP TechEd 08 / <COMP273> Page 82

Exceptions Within the Debugger


Exception objects are only created if they are really accessed
CATCH cx_some_exception INTO exc. CLEANUP INTO exc.

If set, exception objects are always created in debugger


SAP 2008 / SAP TechEd 08 / <COMP273> Page 83

Exceptions Within the Old Debugger

Show exception object

Display
exception

position

SAP 2008 / SAP TechEd 08 / <COMP273> Page 84

Exceptions Versus Return Codes


Don't use exceptions when return codes are more appropriate Ask yourself
Is the situation really exceptional? Are we in an error condition? (No easy question, answer depends on model.)

Examples
Method find, situation "element not found": Neither exceptional nor an error return code Method delete, situation "element to be deleted doesn't exist": Is element expected to exist? yes exception, no return code Method show, situation "page not found": Exceptional exception

Don't use sy-subrc to pass the return code!

SAP 2008 / SAP TechEd 08 / <COMP273> Page 85

Enable Exception Reuse 1/2


Exception should represent the error, not describe where the error occurred
Choose appropriate name for exception class Define exception class as general as possible ( define exception attributes), but as specific as necessary Always have in mind that someone might want to reuse your exception class By raising instances of existing exception classes in new coding By inheriting from class or adding additional exception text ids

Reuse exception only if it's really appropriate


All attributes are meaningful and have the same meaning for all exception ids Exception text is suitable Reuse only for same (or very similar) error situation if there is a good possibility that handlers might react differently to two error situations, using one exception class is not a good idea
SAP 2008 / SAP TechEd 08 / <COMP273> Page 86

Enable Exception Reuse 2/2


Example: We have two operations (methods) with the following error situations:
modify modifies an entry in a database table, it is an error if the specified entry does not exist or if the modification would produce duplicate keys delete deletes an entry in a database table, it is an error if the specified entry does not exist (similarities with the ABAP statements modify and delete are intended)

Example for bad exceptions


cx_ex_modify_error and cx_ex_delete_error

Example for good exceptions


cx_ex_unknown_entry and cx_ex_duplicate_key Both exceptions have an attribute operation or they might inherit it from a common super-class

SAP 2008 / SAP TechEd 08 / <COMP273> Page 87

Choosing the Right Exception Category 1/3


Can exception be precluded?
CX_DYNAMIC_CHECK

Yes No

CX_STATIC_CHECK

CX_NO_CHECK

CX_DYNAMIC_CHECK:
Programmers can avoid exception: they know that the exception will never occur at specific code positions, e.g., by performing a (simple) test beforehand Examples: parameter constraints (cx_sy_zerodivide), call sequence constraints or combination of both (cx_sy_file_open_mode) Note: if test beforehand is not natural or too expensive (e.g., computing the free memory before creating a new object), this category is not the right one

CX_STATIC_CHECK and CX_NO_CHECK:


Programmer cannot preclude that exception will occur (without performing specific complicated tests beforehand)
SAP 2008 / SAP TechEd 08 / <COMP273> Page 88

Choosing the Right Exception Category 2/3


Responsibility for handling exception
Declared Clear
CX_DYNAMIC_CHECK

Undeclared

CX_STATIC_CHECK

CX_NO_CHECK

CX_STATIC_CHECK and CX_DYNAMIC_CHECK:


Clear responsibility: if exception leads to a runtime error, it is easy to see who has not taken the exception into account: the procedure without the RAISING clause (which is listed in the short dump) Note: if most callers cannot handle the exception, the declaration becomes counterproductive these categories are not the right ones

CX_NO_CHECK:
Case-by-case analysis necessary to decide in which procedure the exception should have been caught. No handler ( runtime error) might also be OK Handler might be difficult to write (e.g., for exhausted resource) Handler can be far up in the call hierarchy (if there is just a global solution)
SAP 2008 / SAP TechEd 08 / <COMP273> Page 89

Choosing the Right Exception Category 3/3


Compiler checks are

More helpful
CX_DYNAMIC_CHECK

More harmful

CX_STATIC_CHECK

CX_NO_CHECK

CX_STATIC_CHECK:
Programmers are forced to react to exception by handling it or by propagating it Compiler warns if programmers have forgotten to do so Note: do not annoy programmers by forcing them to write handlers if there is no need to do so they would do the worst: writing empty handlers

CX_DYNAMIC_CHECK and CX_NO_CHECK:


Programmers are free to choose how to take exceptions into account (in ways which a compiler might not recognize) Programmers might forget to take exception into account there is no safety check by the compiler
SAP 2008 / SAP TechEd 08 / <COMP273> Page 90

Exceptions in Layered Software 1/2

Software is usually layered


User Interface Interface to Layer n Implementation of Layer n ..... ..... Interface to Layer 1 Implementation of Layer 1 Interface to Layer 0 Implementation of Layer 0

Exceptions part of the layers' interfaces Abstraction in exceptions from bottom to top Bottom: more technically oriented Top: more semantic/user oriented

SAP 2008 / SAP TechEd 08 / <COMP273> Page 91

Abstraction

Exceptions in Layered Software 2/2


User of a layer should only know the interface, not the implementation of the layer Two ways of abstraction
Use more general exception class from the hierarchy in the RAISING clause instead of listing specific exceptions explicitly Catch exceptions that are implementation specific and map to appropriate new exceptions (use chaining to have a link to the original exception) But: mapping might be inappropriate for many exceptions of category CX_NO_CHECK (their specific handlers have no chance to catch the exception directly)

Mapping of exceptions is usually preferred to generalization


RAISE EXCEPTION TYPE cx_level1_exception EXPORTING previous = exc_level0.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 92

Guarantee a Consistent State


Always use CLEANUP Always anticipate exception propagation of called procedures (esp. of category CX_NO_CHECK) De-allocate global resources after having them allocated (e.g., close a file after a file-open) Ensure atomicity of actions by canceling the performed sub-actions (e.g., cancel the money transfer if the item is out-of-stock) Set the object to a consistent state TRY-construct without a handler possible
METHOD store_result OPEN DATASET file ... TRY. process_data( ). CLEANUP. CLOSE DATASET file. ENDTRY. CLOSE DATASET file. ENDMETHOD.
SAP 2008 / SAP TechEd 08 / <COMP273> Page 93

Writing Correct Exception Handlers 1/2


What to do in an exception handler
Fix things up and retry your operation (avoid infinite loops!), e.g., delete some temporary files if the file system is full and retry writing the file Use an alternative way to produce the same (or a similar) result, e.g., read value from the database instead of looking it up in a corrupt cache Re-raise the exception, e.g., if you cannot handle it if some attribute has specific values (remember: no handler leads to automatic propagation) Map the exception to a more abstract exception (use chaining!) If necessary, map the exception to a return code, an old exception or an exception having the right category Write a log entry and proceed with the next sub-task, e.g., when performing individual tests in a test suite At user interface: display a corresponding message and list options for various ways how to proceed

SAP 2008 / SAP TechEd 08 / <COMP273> Page 94

Writing Correct Exception Handlers 2/2


What to do in an exception handler
Never do nothing empty handlers are always wrong, the extended syntax checks looks for empty handlers If you do not know what to do, do not write a handler (exceptions are automatically propagated to someone who might know what to do)

Catch exceptions selectively


Catch only exceptions for which you can write a useful handler When writing a handler for two or more exception classes, list these classes in the CATCH clause, not a common super-class But: keep abstraction (via generalization) in mind Except at top-level (e.g., if you write a global dispatcher), catching CX_ROOT or CX_NO_CHECK is almost never appropriate, catching CX_STATIC_CHECK and CX_DYNAMIC_CHECK is also critical

SAP 2008 / SAP TechEd 08 / <COMP273> Page 95

Resumable Exceptions
Motivation
Error situation can often be handled only outside service which detects it ( exceptions would be optimal), but is often not severe enough to terminate a whole service, e.g. in mass-data processing ( existing exceptions not usable).

Resumable exceptions
Service can specify that it is able to continue doing its work RAISE RESUMABLE EXCEPTION Handler can decide whether to terminate the service (the default) or to resume RESUME (only possible if allowed by raising statement and all intermediate callers, test by checking attribute is_resumable) Intermediate callers can control resumption of propagated exceptions RAISING ... RESUMABLE(cx)
SAP 2008 / SAP TechEd 08 / <COMP273> Page 96

Exceptions Exercise

Exercise 6: Open the transaction SE80. Create a new report ZTBEXERCISE6_<counter>. Open the report ZTBEXERCISE6_BASE and copy the local test class LTCL_ADV_EXCEPTIONS_TESTS into the newly created report. Have a look at the class ZCL_FILESYSTEM which is a very simple fake implementation of a file system. Find out what exceptions the method ADD_FILE might throw. Start implementing the test method RETRY_RESUME_EXCEPTION by creating an instance of the class ZCL_FILESYSTEM. Now, use the instance to add a new file to the file system. Make sure you catch all exceptions. The exception ZCX_FILE_ALREADY_EXISTS is resumable so make sure you use the correct syntax for the catch block. React appropriately to all exceptions. If there is no space on the file system left call the appropriate method to empty the recycle bin and retry. If the file already exists overwrite it by resuming the method call. In the end make sure by checking the return value of the method ADD_FILE that the file was successfully added to the file system. Debug your application and observe the program flow. Optional: Have a look at the exception ZCX_FILE_ALREADY_EXISTS and find out how it uses a message class + a class attribute to generate the exception text.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 97

Conclusion
Exceptions enable programmers to write robust applications: the software is be able to recover from faults without substantially increasing the code complexity. but Error handling code (whether using exceptions or not using them) is more likely to contain software bugs than any other part of an application (increased complexity, difficult to test). The mere use of exceptions in a program does not imply a disciplined error management. (Douglas Thain)

SAP 2008 / SAP TechEd 08 / <COMP273> Page 98

Agenda

1. Static tests
1.1. Code Inspector

2. Dynamic tests
2.1. Test Driven Development with ABAP Unit 2.2. Coverage Analyser 3.3. ABAP Unit Browser

3. Robust code
3.1. Exceptions 3.2. Asserts

SAP 2008 / SAP TechEd 08 / <COMP273> Page 99

Assertions: Introduction
To write correct and maintainable programs make your assumptions and intentions explicit some_code. some_code. * the following condition should hold: v < 300000 more_code. more_code. Better than an informal comment: special statement assertion some_code. some_code. ASSERT v < 300000. " nothing is faster than light more_code. more_code.

Assertions are available with WEB AS 6.20 SP29

SAP 2008 / SAP TechEd 08 / <COMP273> Page 100

Assertions
Definition An assertion is a condition (Boolean expression) which must be true during program execution
Program language construct which allows to verify consistent state by checking explicit assumptions at specific points during the execution of the program

ABAP statement
ASSERT <log_expr>.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 101

Assertions

ASSERT <log_expr>. An assertion is violated if the expression <log_expr> does not evaluate to true when processing the ASSERT statement This indicates an error in the coding Violating an (always active) assertion terminates the program with runtime error ASSERTION_FAILED Assertions make implicit errors explicit.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 102

Assertions: Benefits During Development and Test


unexpected behavior : assertion

system state

system state

normal termination

consistent state program flow

consistent state program flow

Execution is terminated as soon as incorrect state is detected limit the effect of bugs
SAP 2008 / SAP TechEd 08 / <COMP273> Page 103

enhance program correctness

normal termination

runtime error

Assertions: Benefits During Development and Test


: assertion

system state

undetected error normal termination

system state

consistent state program flow

consistent state program flow

Also finds bugs which only temporarily cause an incorrect state find more bugs
SAP 2008 / SAP TechEd 08 / <COMP273> Page 104

enhance program correctness

normal termination

runtime error

Assertions: Additional Benefits During Maintenance


runtime error or unexpected behavior

system state

?
Where did things start going wrong consistent state not stated explicitly program flow

system state

: assertion

consistent state program flow

Assertions provide insight into expected system behavior by making assumptions explicit enhances maintainability
SAP 2008 / SAP TechEd 08 / <COMP273> Page 105

DEMO
SAP 2008 / SAP TechEd 08 / <COMP273> Page 106

Assertions in Productive Systems


Example
METHOD sort_by_name. the_sorting_algorithm. complicated_stuff. ASSERT itab->is_sorted_by_name( ) = abap_true. ENDMETHOD.

Problem
evaluating the assertion might be expensive not feasible in productive system

SAP 2008 / SAP TechEd 08 / <COMP273> Page 107

Assertions in Productive Systems


Solution
evaluate expensive assertions only during development, testing and maintenance in productive systems, do not evaluate assertions unless a problem has to be investigated activatable assertions METHOD sort_by_name. the_sorting_algorithm. complicated_stuff. ASSERT ID test_sorting CONDITION itab->is_sorted_by_name( ) <> ' '. ENDMETHOD.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 108

Assertions That Can be Activated

ASSERT ID <group> CONDITION <log_expr>. By specifying addition ID <group> the ASSERT statement is linked to checkpoint group <group> and can be activated Activatable assertions are inactive by default, unless activation is set for the corresponding checkpoint group (in contrast to always active assertions, which are always active and can not be disabled) Inactive ASSERT statements are ignored, the corresponding conditions are not evaluated Time consuming checks can be coded into assertions that can be activated, without degrading application performance in a productive environment

SAP 2008 / SAP TechEd 08 / <COMP273> Page 109

Checkpoint Groups
Checkpoint Group is a new workbench object type which is embedded into WB navigation and cross reference. It is used to control activatable checkpoint statements (e.g. ASSERT) Associated maintenance transaction (SAAB) can be called directly or via object navigator

Transaction SAAB
Activation of activatable Assertion is set dynamically via the specified checkpoint group by means of activation settings Assertions can be activated in a running system

SAP 2008 / SAP TechEd 08 / <COMP273> Page 110

Activation Settings: Overview


An activation setting consists of three components
Scope: To which ASSERT statements does it apply? Target: For which sessions is it effective? Mode: What will happen when the assertion is violated? Checkpoint Group AAB_DEMO User TESTUSER Server * Mode ABORT

An activatable ASSERT statement is ignored unless an activation setting with matching scope and target specification is found.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 111

Activation Settings: Scope


A setting only applies to those ASSERT statements which are linked to the specified checkpoint group
ASSERT ID aab_demo CONDITION is_sorted( ) = abap_true.

Checkpoint Group AAB_DEMO

User TESTUSER

Server *

Mode ABORT

ASSERT ID some_other_group CONDITION num < 100.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 112

Activation Settings: Target

Checkpoint Group AAB_DEMO

User TESTUSER

Server *

Mode ABORT

User * User * User TESTUSER

Server * Server pwdf0195 Server *

All users on all servers: Global activation All users on specified server: Server specific activation Specified user on all servers: User specific activation Special case: Personal activation

All target settings are client dependent (as of 7.00)


SAP 2008 / SAP TechEd 08 / <COMP273> Page 113

Activation Settings: Mode

Checkpoint Group AAB_DEMO

User TESTUSER

Server *

Mode ABORT

What will happen when the assertion is violated?


ABORT Runtime error ASSERTION_FAILED BREAK Program execution is stopped (Debugger) (Two variant BREAK/LOG and BREAK/ABORT define what to do during batch run instead starting the debugger) LOG Violation is logged INACTIVE Violation is ignored (Activation Setting with Mode INACTIVE will be ignored)

Assertions which are always active (no ID <group> specified) always run in mode ABORT.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 114

Activation Mode
Activation mode and maintenance scenarios
Maintenance

Short term, interactive

Long term, non-interactive

BREAK

ABORT

LOG

Support user, prepared to jump into debugger

Productive user, prepared to encounter short dump

Productive user, non disturbed

Support user, analyses short dumps and monitors assertion logs

SAP 2008 / SAP TechEd 08 / <COMP273> Page 115

Multiple Activation Settings

Checkpoint Group AAB_DEMO AAB_DEMO AAB_DEMO AAB_DEMO

User * * * TESTUSER 1

Server * SERVER1 SERVER2 *

Mode ABORT LOG BREAK LOG

Multiple settings with the same scope (checkpoint group) but different target (user, server) can be specified simultaneously precedence rule defines which setting will be used to determine the activation mode

SAP 2008 / SAP TechEd 08 / <COMP273> Page 116

Multiple Activation Settings: Precedence Rule


User specific setting supersedes server specific setting supersedes global setting USER2 on SERVER3 USER2 on SERVER1 USER2 on SERVER2

Checkpoint Group AAB_DEMO AAB_DEMO AAB_DEMO AAB_DEMO

User * * * USER1

Server *

Mode ABORT

SERVER LOG 1 SERVER BREAK 2 * LOG

USER1 on SERVER2
SAP 2008 / SAP TechEd 08 / <COMP273> Page 117

DEMO
SAP 2008 / SAP TechEd 08 / <COMP273> Page 118

Maintaining Settings: Personal Activation

Transaction SAAB

Set personal activation here


SAP 2008 / SAP TechEd 08 / <COMP273> Page 119

Maintaining Settings: User/Server Specific Activation


Transaction SAAB

User-specific Settings
Break Break/Log Break/Abort Abort

Server-specific Settings

SAP 2008 / SAP TechEd 08 / <COMP273> Page 120

Maintaining Settings: Considerations


Be careful with all kinds of non-personal settings
Users will be disturbed if their application stops or terminates suddenly, especially in productive environments Performance is possibly degraded Use non-personal activation only after careful consideration non-personal settings will be sys-logged

Authority checks performed on activation


Personal activation requires debug authorization (display) Non-personal activation requires debug authorization (change) and process administration authorization

SAP 2008 / SAP TechEd 08 / <COMP273> Page 121

Assertion Log
A dedicated logging facility exists for assertion violations
Switched on via activation mode LOG Log entries are viewed using transaction SAAB

Transaction SAAB

SAP 2008 / SAP TechEd 08 / <COMP273> Page 122

Assertion Log: Subkey


To conserve space, we use aggregation
Log entries are aggregated for same ASSERT statement Information is only available for last violated assertion

Addition SUBKEY to reduce aggregation


ASSERT ID group SUBKEY subkey CONDITION cond Log entries are aggregated for same ASSERT statement with the same subkey value

SAP 2008 / SAP TechEd 08 / <COMP273> Page 123

Assertion Log: Fields


Default log information
Checkpoint group Source position: program, include, line number, procedure Violation count (aggregation) Date and time of last violation

Addition FIELDS for additional information


ASSERT ID group FIELDS f1 fn CONDITION cond names and values of fields f1 fn are stored in the log when running in ABORT mode, field names and values are listed in runtime error ASSERTION_FAILED

SAP 2008 / SAP TechEd 08 / <COMP273> Page 124

Activation Variants
Reusing (complex) activation settings
When working with a set of checkpoint groups, you may want to store your complex settings You may want to transport the stored settings In order to be reusable by other users, the stored settings must not contain target specifications Activation Variant

An activation variant is a workbench object containing template settings for a list of checkpoint groups. The target specification (user, server) is not stored in the activation variant, but has to be specified when activating via the variant.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 125

Maintaining Activation Variants

Transaction SAAB

List of checkpoint groups (scope specification)

Corresponding modes

SAP 2008 / SAP TechEd 08 / <COMP273> Page 126

Variant Activation

Transaction SAAB

Activation target is specified when activation variant is activated. Variant is expanded and setting is applied for each contained checkpoint group.

SAP 2008 / SAP TechEd 08 / <COMP273> Page 127

Scope Definition by Compilation Unit


Normally the scope of an activation setting is specified using a checkpoint group. In some cases it may be advantageous to specify the scope using a compilation unit (program, class or function group). All activatable ASSERT statements within the specified compilation unit are controlled with such a setting, regardless of the respective linkage to individual checkpoint groups Precedence rule:

Setting via compilation unit supersedes setting via checkpoint group

SAP 2008 / SAP TechEd 08 / <COMP273> Page 128

Scope Definition by Compilation Unit: Example

ASSERT ID A ASSERT ID B

ASSERT ID D ASSERT ID E

ASSERT ID F ASSERT ID A

ASSERT ID C report x application

ASSERT ID A class y

ASSERT ID E function group z

Activation mode ABORT for checkpoints in group A Activation mode BREAK for checkpoints in class y

SAP 2008 / SAP TechEd 08 / <COMP273> Page 129

Specifying Settings for a Compilation Unit


Settings for compilation units can only be specified using activation variants

Transaction SAAB

Transaction SAAB

Compilation units
SAP 2008 / SAP TechEd 08 / <COMP273> Page 130

Conclusions
ABAP assertions support the developer in writing correct code Code instrumented with assertions is easier to support and maintain, as the developer explicitly declares his assumptions using assert conditions ABAP assertions are either always active, or can be activated on the fly and without program modification or recompilation (optionally user or server specific) Activation can be controlled via checkpoint group or compilation unit

SAP 2008 / SAP TechEd 08 / <COMP273> Page 131

Fuel your Career with SAP Certification

What the industry is saying


Teams with certified architects and developers deliver projects on specification, on time, and on budget more often than other teams.
2008 IDC Certification Analysis

82% of hiring managers use certification as a hiring criteria.


2008 SAP Client Survey

SAP Certified Application Professional status is proof of quality, and thats what matters most to customers.*
Conny Dahlgren, SAP Certified Professional

Take advantage of the enhanced, expanded and multi tier certifications from SAP today!
SAP 2008 / SAP TechEd 08 / <COMP273> Page 132

Thank you!

SAP 2008 / SAP TechEd 08 / <COMP273> Page 133

Feedback Please complete your session evaluation.


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

Thank You !
SAP 2008 / SAP TechEd 08 / <COMP273> Page 134

Building Your Business with SDN Subscriptions SDN Subscriptions offers developers and consultants like you, an annual license to the complete SAP NetWeaver platform software, related services, and educational content, to keep you at the top of your profession.
SDN Software Subscriptions: (currently available in U.S. and Germany)
A one year low cost, development, test, and commercialization license to the complete SAP NetWeaver software platform Automatic notification for patches and updates Continuous learning presentations and demos to build expertise in each of the SAP NetWeaver platform components A personal SAP namespace

SAP NetWeaver Content Subscription: (available globally)


An online library of continuous learning content to help build skills.

Starter Kit

To learn more or to get your own SDN Subscription, visit us at the Community Clubhouse or at www.sdn.sap.com/irj/sdn/subscriptions
SAP 2008 / SAP TechEd 08 / <COMP273> Page 135

Copyright 2008 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. SAP, R/3, xApps, xApp, SAP NetWeaver, Duet, SAP Business ByDesign, ByDesign, PartnerEdge 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 and associated logos displayed 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.

Weitergabe und Vervielfltigung dieser Publikation oder von Teilen daraus sind, zu welchem Zweck und in welcher Form auch immer, ohne die ausdrckliche schriftliche Genehmigung durch SAP AG nicht gestattet. In dieser Publikation enthaltene Informationen knnen ohne vorherige Ankndigung gendert werden. Einige von der SAP AG und deren Vertriebspartnern vertriebene Softwareprodukte knnen Softwarekomponenten umfassen, die Eigentum anderer Softwarehersteller sind. SAP, R/3, xApps, xApp, SAP NetWeaver, Duet, SAP Business ByDesign, ByDesign, PartnerEdge und andere in diesem Dokument erwhnte SAP-Produkte und Services sowie die dazugehrigen Logos sind Marken oder eingetragene Marken der SAP AG in Deutschland und in mehreren anderen Lndern weltweit. Alle anderen in diesem Dokument erwhnten Namen von Produkten und Services sowie die damit verbundenen Firmenlogos sind Marken der jeweiligen Unternehmen. Die Angaben im Text sind unverbindlich und dienen lediglich zu Informationszwecken. Produkte knnen lnderspezifische Unterschiede aufweisen. Die in dieser Publikation enthaltene Information ist Eigentum der SAP. Weitergabe und Vervielfltigung dieser Publikation oder von Teilen daraus sind, zu welchem Zweck und in welcher Form auch immer, nur mit ausdrcklicher schriftlicher Genehmigung durch SAP AG gestattet. Bei dieser Publikation handelt es sich um eine vorlufige Version, die nicht Ihrem gltigen Lizenzvertrag oder anderen Vereinbarungen mit SAP unterliegt. Diese Publikation enthlt nur vorgesehene Strategien, Entwicklungen und Funktionen des SAP-Produkts. SAP entsteht aus dieser Publikation keine Verpflichtung zu einer bestimmten Geschfts- oder Produktstrategie und/oder bestimmten Entwicklungen. Diese Publikation kann von SAP jederzeit ohne vorherige Ankndigung gendert werden. SAP bernimmt keine Haftung fr Fehler oder Auslassungen in dieser Publikation. Des Weiteren bernimmt SAP keine Garantie fr die Exaktheit oder Vollstndigkeit der Informationen, Texte, Grafiken, Links und sonstigen in dieser Publikation enthaltenen Elementen. Diese Publikation wird ohne jegliche Gewhr, weder ausdrcklich noch stillschweigend, bereitgestellt. Dies gilt u. a., aber nicht ausschlielich, hinsichtlich der Gewhrleistung der Marktgngigkeit und der Eignung fr einen bestimmten Zweck sowie fr die Gewhrleistung der Nichtverletzung geltenden Rechts. SAP haftet nicht fr entstandene Schden. Dies gilt u. a. und uneingeschrnkt fr konkrete, besondere und mittelbare Schden oder Folgeschden, die aus der Nutzung dieser Materialien entstehen knnen. Diese Einschrnkung gilt nicht bei Vorsatz oder grober Fahrlssigkeit. Die gesetzliche Haftung bei Personenschden oder Produkthaftung bleibt unberhrt. Die Informationen, auf die Sie mglicherweise ber die in diesem Material enthaltenen Hotlinks zugreifen, unterliegen nicht dem Einfluss von SAP, und SAP untersttzt nicht die Nutzung von Internetseiten Dritter durch Sie und gibt keinerlei Gewhrleistungen oder Zusagen ber Internetseiten Dritter ab. Alle Rechte vorbehalten.
SAP 2008 / SAP TechEd 08 / <COMP273> Page 136

You might also like