+ All Categories
Home > Documents > BulletproofABAP

BulletproofABAP

Date post: 08-Oct-2014
Category:
Upload: joao-paulo-mendes
View: 214 times
Download: 0 times
Share this document with a friend
Popular Tags:
136
COMP273 Test-Driven and Bulletproof ABAP Development Stefan Bresch, SAP AG NW F ABAP Thomas Ritter, SAP AG NW F ABAP
Transcript
Page 1: BulletproofABAP

COMP273 Test-Driven and Bulletproof ABAP

Development

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

Page 2: BulletproofABAP

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

Disclaimer

This presentation outlines our general product direction and should not be relied on in making a purchase decision. This presentation is not subject to your license agreement or any other agreement with SAP. SAP has no obligation to pursue any course of business outlined in this presentation or to develop or release any functionality mentioned in this presentation. This presentation and SAP's

strategy and possible future developments are

subject to change and may be changed by SAP at any time for any reason without notice. This document is provided without a warranty of any kind, either express or implied, including but not limited to, the implied warranties of merchantability, fitness for a particular purpose, or non-infringement. SAP assumes no responsibility for errors or omissions in this document, except if such damages were caused by SAP intentionally or grossly negligent.

Page 3: BulletproofABAP

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

Agenda (Warm Up)

“Everything that can possibly go wrong will go wrong” (Murphy’s Law)

Page 4: BulletproofABAP

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

1.

Static checks1.1.

Code Inspector

2.

Dynamic tests2.1.

Test Driven Development with ABAP Unit

2.2.

Coverage Analyzer3.3. ABAP Unit Browser

3.

Robust code3.1.

Exceptions

3.2.

Asserts

Agenda

Page 5: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 5

Static Checks: Code Inspection From The 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).

ABAP Editor

Code inspector is available with WEB AS 6.10

for R/3 >= 46C a transport is available -> note 543359

Page 6: BulletproofABAP

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

DEMO

Page 7: BulletproofABAP

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

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*

Page 8: BulletproofABAP

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

1.

Static tests1.1.

Code Inspector

2.

Dynamic tests2.1.

Test Driven Development with ABAP Unit

2.2.

Coverage Analyzer3.3. ABAP Unit Browser

3.

Robust code3.1.

Exceptions

3.2.

Asserts

Agenda

Page 9: BulletproofABAP

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

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.

Page 10: BulletproofABAP

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

Introduction Unit Tests II

BenefitsA 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.

Page 11: BulletproofABAP

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

Introduction ABAP Unit I

ABAP Unit is the official xUnit

testing framework for ABAP. Its most remarkable features are:

1.

Tightly integrated into the programming language2.

Production code and unit test code are bundled and transported together3.

Test code cannot be executed in a production system.

ABAP Unit is available with NetWeaver 04.

Page 12: BulletproofABAP

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

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.

Page 13: BulletproofABAP

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

For testing: used to mark classes as test classes and methods as

test methods.

ABAP Unit –

For testing

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

Define class as test class

Page 14: BulletproofABAP

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

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

ABAP Unit –

Risk Level

CLASS ltcl_flight

DEFINITION FOR TESTING

RISK LEVEL HARMLESS

DURATION SHORT.

PRIVATE SECTION.METHODS: test_create_flight

FOR TESTING.

ENDCLASS.

Define risk level

Page 15: BulletproofABAP

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

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

ABAP Unit –

Duration

CLASS ltcl_flight

DEFINITION FOR TESTING

RISK LEVEL HARMLESS DURATION SHORT.

PRIVATE SECTION.METHODS: test_create_flight

FOR TESTING.

ENDCLASS.

Define duration

Page 16: BulletproofABAP

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

Profile parameter: abap/test_generation

Transaction: SAUNIT_CLIENT_SETUP

ABAP Unit –

System Configuration

Page 17: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 17

ABAP Unit –

Assert Methods

Assert methods:used to determine whether a test is successful or notthe 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

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.

Example:

Page 18: BulletproofABAP

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

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

ABAP Unit –

Execute Tests

Page 19: BulletproofABAP

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

ABAP Unit –

Result Display

Page 20: BulletproofABAP

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

DEMO

Page 21: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 21

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

durationshort

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?

Page 22: BulletproofABAP

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

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.

Page 23: BulletproofABAP

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

ABAP Unit –

Test Execution

ABAP Unit test execution flow:

class_setup()

setup()

test method

teardown()

class_teardown()

Setup forall tests

Setup foreach test method

Execute testmethod

Teardown foreach test method

Teardown forall tests

Page 24: BulletproofABAP

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

Example test class:

ABAP Unit –

How to Define Fixture Methods

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

Page 25: BulletproofABAP

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

Test Driven Development -

Motivation

Common problems with the “classic”

unit testing approachTests are written too late or not at allThe production code is not testableTest coverage is low

Page 26: BulletproofABAP

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

Test Driven Development -

Motivation

One solution:

Write the unit tests before the production code!

Page 27: BulletproofABAP

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

Test Driven Development -

Process

Write test

Make it compile

Test fails

Refactor

Make the test pass

Page 28: BulletproofABAP

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

DEMO

Page 29: BulletproofABAP

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

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

Page 30: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 30

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 data: stack type ref to ZCL_STACK.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

Page 31: BulletproofABAP

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

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 seeIf it’s 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 toPrivate methods cannot be tested easily however ABAP Objects friends feature

offers a solution.Simplicity: The simpler, the easier it‘s too testLong methods are usually hard to test because they are responsible for handling

too many different things.

Page 32: BulletproofABAP

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

ABAP Unit –

Testability

Best practices for testability:clear separation between persistence, application, and UI codingobject 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

Page 33: BulletproofABAP

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

1.

Static tests1.1.

Code Inspector

2.

Dynamic tests2.1.

Test Driven Development with ABAP Unit

2.2.

Coverage Analyzer3.3. ABAP Unit Browser

3.

Robust code3.1.

Exceptions

3.2.

Asserts

Agenda

Page 34: BulletproofABAP

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

Coverage Analyzer

Coverage Analyzer is available with WEB AS 6.10

The Coverage Analyzer is a tool for monitoring the system-wide execution

of ABAP programs.

You canmonitor which programs and even which modules of a program were covered by a testfind 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

Page 35: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 35

Coverage Analyzer

Make sure that the coverage analyzer is running properly on your server before testing!

/nscov

SAP Easy Access

/nscov

Page 36: BulletproofABAP

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

Coverage Analyzer –

Global View (QM)

Page 37: BulletproofABAP

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

Coverage Analyzer –

Detail View

Check which modularization units of your programs were executed

(covered) during a test.

Page 38: BulletproofABAP

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

DEMO

Page 39: BulletproofABAP

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

1.

Static tests1.1.

Code Inspector

2.

Dynamic tests2.1.

Test Driven Development with ABAP Unit

2.2.

Coverage Analyzer3.3.

ABAP Unit Browser

3.

Robust code3.1.

Exceptions

3.2.

Asserts

Agenda

Page 40: BulletproofABAP

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

ABAP Unit Browser -

Introduction

ABAP Unit Browser is available with SAP NetWeaver

7.1

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.

Page 41: BulletproofABAP

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

ABAP Unit Browser –

Create new favorite

1. Create a new favorite

Page 42: BulletproofABAP

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

ABAP Unit Browser –

Add Test Classes

2. Add test classes to the favorite

Page 43: BulletproofABAP

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

ABAP Unit Browser –

Configure Execution Options

3. Add coverage measurement

Page 44: BulletproofABAP

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

ABAP Unit Browser –

Execute Favorite

4. Execute tests

Page 45: BulletproofABAP

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

ABAP Unit Browser –

Analyze Results

5. Analyze results

Page 46: BulletproofABAP

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

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.

Page 47: BulletproofABAP

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

1.

Static tests1.1.

Code Inspector

2.

Dynamic tests2.1.

Test Driven Development with ABAP Unit

2.2.

Coverage Analyzer3.3. ABAP Unit Browser

3.

Robust code3.1.

Exceptions

3.2.

Asserts

Agenda

Page 48: BulletproofABAP

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

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

Page 49: BulletproofABAP

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

Available Since…

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

Page 50: BulletproofABAP

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

Principles of Exception Handling 1/2

Look at software as a (layered) collection of services

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

Best way to deal with error situationSignal what went wrong, passing along additional informationPass flow of control to a suitable handler which is able to react to that particular situation

RequirementsSeparation of normal coding from error handler codingSelective definition of handlers for certain errorsAutomatic abort of routine, that cannot provide promised service(→ automatic propagation along call chain)

Page 51: BulletproofABAP

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

Principles of Exception Handling 2/2

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

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

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

In principle comparable to Java, C++

Page 52: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 52

Raising Class-Based Exceptions

Raise exception with implicit object creation

RAISE EXCEPTION TYPE

cx_page_not_found

EXPORTING

page

= 'http://www.sap.com/shop/'.

DATA excp

TYPE REF TO

cx_page_not_found.

CREATE OBJECT

excp

EXPORTING

page

= 'http://www.sap.com/shop/'.

RAISE EXCEPTION

excp.

x = 1 / 0.

"creates exception

cx_sy_zerodivide

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

Exception raised by kernel (runtime exception)

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

Page 53: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 53

Catching Class-Based Exceptions

Syntactical construct:

TRY..ENDTRY

DATA excp

TYPE REF TO

cx_sy_file_open_mode.

TRY.

CATCH

cx_sy_file_open_mode

INTO excp.

CATCH

cx_sy_file_access_error

ENDTRY.

OPEN DATASET file FOR OUTPUT IN BINARY MODE.TRANSFER xbuffer

TO file.

CLOSE DATASET file.WRITE: 'Buffer successfully written'.

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

WRITE: 'Other file IO exception occurred'.

Consists ofExactly one protected code areaOne or more exception handlers

Page 54: BulletproofABAP

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

Protected Area

TRY.

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

Handler code is not protectedBut TRY constructs can be nested

CATCH cx_e1 ... cx_eN

[ INTO excp1 ].

CATCH cx_f1 ... Cx_fM

[ INTO excp2 ].

...

ENDTRY.

"–

handler code for exceptions cx_e1 ..cx_eN

"–

handler code for exceptions cx_f1 ..cx_fM

"–

any statements

Page 55: BulletproofABAP

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

Exception Handlers

Exception handlers

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

Optional access to exception object by

INTO clause

TRY."–

any statements

CATCH

cx_e1 ... cx_eN

[ INTO

excp1 ].

CATCH

cx_f1 ... cx_fN

[ INTO

excp2 ].

...

ENDTRY.

"–

handler code for exceptions cx_e1 ..cx_eN

"–

handler code for exceptions cx_f1 ..cx_fN

Page 56: BulletproofABAP

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

Grouping by Polymorphism

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

Order of clauses is important

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

CX_ROOT

CX_PAGE_NOT_FOUND

CX_SY_ARITHMETIC_ERROR

CX_SY_ZERODIVIDE CX_SY_ARITHMETIC_OVERFLOW

Page 57: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 57

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.

Page 58: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 58

Automatic Exception Propagation

METHOD retrieve.

"IMPORTING a_page

TYPE string

RAISE EXCEPTION TYPE

cx_page_not_found

ENDMETHOD.

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.

TRY.

dispatcher->show( a_page

).

" --

More normal coding CATCH

cx_page_not_found

cx_misformed_url.

" --

Error handling. ENDTRY.

Page 59: BulletproofABAP

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

How to Find the Right Exception Handler

Exception occurred

Inside protected

area?

Look for handler in corresponding

TRY-block

Handler found?

Go up call hierarchy and look for outer

TRY-block

TRY-block found?

yes

no

yes

no

Runtime Error

no

Process handler

code

Go to end of handler's

TRY-block

yes

Page 60: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 60

How to Guarantee a Consistent State

TRY."–

any statements

CATCH cx_e1 ... cx_eN

[ INTO excp1 ].

...

CLEANUP

[ INTO excp

].

"-

optional

ENDTRY.

"–

handler code for exceptions cx_e1 ..cx_eN

"–

statements

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

SolutionIntroduction of (optional) CLEANUP clause

Page 61: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 61

Example CLEANUP Clause

METHOD retrieve.

"IMPORTING a_page

TYPE string

RAISE EXCEPTION TYPE

cx_page_not_found

ENDMETHOD.

METHOD show.

"IMPORTING a_page

TYPE string

TRY.

retrieve( a_page

).

CATCH cx_some_exception.

" --

Error handling for some exception. CATCH cx_other_exception.

" --

Error handling for other exception. ENDTRY.

ENDMETHOD.

TRY.

dispatcher->show( a_page

).

CATCH

cx_page_not_found

cx_misformed_url.

" --

Error handling. ENDTRY.

METHOD show.

"IMPORTING a_page

TYPE string

TRY.

retrieve( a_page

).

CATCH cx_some_exception.

" --

Error handling for some exception. CATCH cx_other_exception.

" --

Error handling for other exception.

ENDTRY.

ENDMETHOD.

METHOD show.

"IMPORTING a_page

TYPE string

TRY.

retrieve( a_page

).

CATCH cx_some_exception.

" --

Error handling for some exception. CATCH cx_other_exception.

" --

Error handling for other exception.

ENDTRY.

ENDMETHOD.

METHOD show.

"IMPORTING a_page

TYPE string

TRY.

retrieve(a_page).

CATCH cx_some_exception.

" --

Error handling for some exception. CATCH cx_other_exception.

" --

Error handling for other exception.

ENDTRY.

ENDMETHOD.

CLEANUP.

" --

Free internal resources.

Page 62: BulletproofABAP

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

CLEANUP Clause

CLEANUP clause is processed if and only if exceptionHas occurredIs not caught in current TRY – constructIs going to be caught somewhere above in call hierarchy

Technically spoken

CLEANUP clause is processed during unwinding of the stack

At the end of

CLEANUP clause, execution continues with next higher

CLEANUP clause or handler code respectively

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

Page 63: BulletproofABAP

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

Declaring Exceptions

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

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

METHODS: show IMPORTING a_page

TYPE string

RAISING

cx_page_not_found.

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

Page 64: BulletproofABAP

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

RAISING Clause

Declaration in subroutines (forms), function modules and methods

... RAISING

cx_e1 cx_e2 ... cx_eN

Each class mentioned in RAISING clause implies all subclasses

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

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

Page 65: BulletproofABAP

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

Exceptions in Procedure Declarations

How to declare exceptions in class / function builder

Use class-based exceptions

Page 66: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 66

Limitations of Static Checking (1)

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

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

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

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

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

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

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

Page 67: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 67

Limitations of Static Checking (2)

For some exceptions, users can ensure that they will not occurThey know(!) what they are doing or they can avoid error conditions beforehandTypical examples: parameter constraints (e.g. cx_sy_zerodivide, cx_misformed_url)

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

Leads to empty handlers just to calm compiler down

Problem: what happens, if the exception does occur?

Solution: there are exceptions that must be declared if they can

occur but they are not statically checked

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

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

(cx_sy_no_handler)

Page 68: BulletproofABAP

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

Exception Class Hierarchy

Three categories of exceptions

Signature statically

checked by compiler

and dynamicallyat runtime

Signaturechecked

only at runtime

Not in signature,

never checked

CX_ROOT

CX_DYNAMIC_CHECK CX_NO_CHECKCX_STATIC_CHECK

All exceptions are derived from corresponding classes

Page 69: BulletproofABAP

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

Exception Class Hierarchy

Signature statically

checked by compiler

and dynamicallyat runtime

Signaturechecked

only at runtime

CX_ROOT

CX_DYNAMIC_CHECK CX_NO_CHECKCX_STATIC_CHECK

Can be used in RAISING clause

Not in signature

never checked

Page 70: BulletproofABAP

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

Exception Classes: Methods and Attributes

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

Methods inherited from

cx_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 classesOne optional parameter for each non-private attribute

Page 71: BulletproofABAP

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

Chaining of Exceptions

Attribute

previous:Enables chaining of exceptions

Classname

CX_PAGE_NOT_FOUND

Previous

CX_SY_NO_HANDLER

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

TextidCX_PAGE_NOT_FOUND

Example: undeclared exception leaves procedureException cx_sy_no_handler is raised

Chaining can be employed explicitly

RAISE EXCEPTION TYPE

cx_some_exception

EXPORTING

previous

=

caught_exception.

Page 72: BulletproofABAP

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

Exception Texts

Attribute

textid:

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

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

Textid

CX_PAGE_NOT_FOUND

Method

get_text, get_longtext:Returns textual description of the exceptionOccurrences of ‘&ATTRIBUTE&' in text are substituted by attribute values

Points to textual description of the exception

'No document at URL &PAGE&'

'No document at URL &PAGE&'

Page 73: BulletproofABAP

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

DEMO

Page 74: BulletproofABAP

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

Exception Builder

Substituted by attribute valueDefault exception id

has same name as exception class

Page 75: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 75

Multiple Exception Texts

They can be used to differentiate between related exceptionsNo need to define separate exception classes for sflight variantsShould be really related

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

Raise exception with different textRAISE EXCEPTION TYPE

cx_aab_persistence

EXPORTING

textid

= cx_aab_persistence=>cx_aab_...__flush_fail

Page 76: BulletproofABAP

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

Exception Text Repository

Texts up to 255 characters supportedUse of &ATTRIBUTE& in text for substitutionShould not be used for exceptions with text in user interface

Online Text Repository (OTR)

Messages (T100) —

available with SAP_BASIS 640Texts no longer than 72 charactersOnly 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

Page 77: BulletproofABAP

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

Exceptions Based on Message Class

Page 78: BulletproofABAP

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

Local Exception Classes 1/2

Local exception classes can be definedIn 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 attributesWithout specifying attribute for text you will get a default text

Local exceptions might be useful

Local exceptions should normally be handled locally in a software layer

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

Page 79: BulletproofABAP

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

Local Exception Classes 2/2

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

OTR-TextsFor each exception id one constant of type SOTR_CONCName is name of exception id, value is respective OTR GUID

T100-TextsImplement IF_T100_MESSAGEFor each exception id one constant of type SCX_T100KEYValues define msgid, msgno and parameter mapping

Page 80: BulletproofABAP

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

Exceptions Within the Debugger

Show exception

objectDisplay

exception position

Page 81: BulletproofABAP

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

Exceptions Within the Debugger

Page 82: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 82

Exceptions Within the Debugger

Condition is valid for subclasses too ⇒

to stop on every exception, set breakpoint at CX_ROOT

You can tell the debugger to stop on certain exceptions

Page 83: BulletproofABAP

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

Exceptions Within the Debugger

Exception objects are only created if they are really accessedCATCH cx_some_exception

INTO exc.

CLEANUP INTO exc.

If set, exception objects are always

created in debugger

Page 84: BulletproofABAP

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

Exceptions Within the Old Debugger

Show exception

object

Display exception

position

Page 85: BulletproofABAP

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

Exceptions Versus Return Codes

Don't use

exceptions when return codes are more appropriate

Ask yourselfIs the situation really exceptional?Are we in an error condition?

(No easy question, answer depends on model.)

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

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

Page 86: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 86

Enable Exception Reuse 1/2

Exception should

represent the error, not describe where the error occurred

Choose appropriate name for exception classDefine exception class as general as possible (→ define exception attributes), but as specific as necessaryAlways have in mind that someone might want to reuse your exception class…

By raising instances of existing exception classes in new codingBy inheriting from class or adding additional exception text ids

Reuse exception only if it's really

appropriateAll attributes are meaningful and have the same meaning for all exception idsException text is suitableReuse 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

Page 87: BulletproofABAP

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

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 keysdelete 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 exceptionscx_ex_modify_error and cx_ex_delete_error

Example for good exceptionscx_ex_unknown_entry and cx_ex_duplicate_keyBoth exceptions have an attribute operation or they might inherit it from a common super-class

Page 88: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 88

Choosing the Right Exception Category 1/3

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

CX_STATIC_CHECK

CX_DYNAMIC_CHECK

CX_NO_CHECK

Can exception be precluded? Yes

No

Page 89: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 89

Choosing the Right Exception Category 2/3

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 counter-productive → 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)

CX_STATIC_CHECK

CX_DYNAMIC_CHECK

CX_NO_CHECK

Responsibility for handling

exception

Declared →

Clear

Undeclared

Page 90: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 90

Choosing the Right Exception Category 3/3

CX_STATIC_CHECK:Programmers are forced to react to exception by handling it or by propagating itCompiler 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

CX_STATIC_CHECK

CX_DYNAMIC_CHECK

CX_NO_CHECK

Compiler checks

are…More helpful

More harmful

Page 91: BulletproofABAP

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

Exceptions in Layered Software 1/2

User Interface

Implementation of Layer n

Interface to Layer n

.....

.....

Implementation of Layer 1

Interface to Layer 1

Implementation of Layer 0

Interface to Layer 0 A

bstr

actio

n

Software is usually layered

Exceptions part of the layers' interfaces

Abstraction in exceptions from bottom to top

Bottom: more technically orientedTop: more semantic/user oriented

Page 92: BulletproofABAP

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

Exceptions in Layered Software 2/2

User of a layer should only know the interface, not the implementation of the layer

Two ways of abstractionUse more general exception class from the hierarchy in the RAISING clause instead of listing specific exceptions explicitlyCatch 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 categoryCX_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.

Page 93: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 93

Guarantee a Consistent State

Always use CLEANUPAlways 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 possibleMETHOD store_result

OPEN DATASET

file ...

TRY.

process_data( ).

CLEANUP.

CLOSE DATASET

file.

ENDTRY.

CLOSE DATASET

file.

ENDMETHOD.

Page 94: BulletproofABAP

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

Writing Correct Exception Handlers 1/2

What to do in an exception handlerFix 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 fileUse 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 cacheRe-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 categoryWrite a log entry and proceed with the next sub-task, e.g., when performing individual tests in a test suiteAt user interface: display a corresponding message and list options for various ways how to proceed…

Page 95: BulletproofABAP

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

Writing Correct Exception Handlers 2/2

What to do in an exception handlerNever do nothing ⇒ empty handlers are always wrong, the extended syntax checks looks for empty handlersIf 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

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

Page 96: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 96

Resumable

Exceptions

MotivationError situation can often be handled only outside service which detects it(→ exceptions would be optimal),but is often not severe enough toterminate a whole service, e.g.in mass-data processing(→ existing exceptions not usable).

Resumable exceptionsService can specify that it is able to continue doing its work→ RAISE RESUMABLE EXCEPTIONHandler 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)

Page 97: BulletproofABAP

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

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_FILEthat 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.

Page 98: BulletproofABAP

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

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)

Page 99: BulletproofABAP

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

1.

Static tests1.1.

Code Inspector

2.

Dynamic tests2.1.

Test Driven Development with ABAP Unit

2.2.

Coverage Analyser3.3. ABAP Unit Browser

3.

Robust code3.1.

Exceptions

3.2.

Asserts

Agenda

Page 100: BulletproofABAP

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

Assertions: Introduction

To write correct and maintainable programs… … make your assumptions and intentions explicit

Better than an informal comment: special statement –

assertion

some_code. some_code.

* the following condition should hold: v < 300000

more_code. more_code.

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

Page 101: BulletproofABAP

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

Definition

Program language construct which allows to verify consistent state by checking explicit assumptions at specific points during the execution of the program

ABAP statement

Assertions

An assertion

is a condition (Boolean expression) which must be true during program execution

ASSERT

<log_expr>.

Page 102: BulletproofABAP

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

Assertions

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.

ASSERT

<log_expr>.

Page 103: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 103

Assertions: Benefits During Development and Test

syst

em s

tate

program flow

consistent stateno

rmal

term

inat

ion

unexpected behavior

syst

em s

tate

program flow

consistent state

norm

al te

rmin

atio

n

: assertion

runtime error

Execution is terminated as soon as incorrect state is detected

limit the effect of bugs enhance program correctness

Page 104: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 104

Assertions: Benefits During Development and Test

syst

em s

tate

program flow

consistent stateno

rmal

term

inat

ion

undetected error

syst

em s

tate

program flow

consistent state

norm

al te

rmin

atio

n

: assertion

runtime error

Also finds bugs which only temporarily cause an incorrect state

find more bugs enhance program correctness

Page 105: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 105

Assertions: Additional Benefits During Maintenance

consistent state not stated explicitly consistent state

: assertion

syst

em s

tate

program flow

syst

em s

tate

program flow

runtime error or unexpected behavior

?Where did things start going wrong

Assertions provide insight into expected system behavior by making assumptions explicit

enhances maintainability

Page 106: BulletproofABAP

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

DEMO

Page 107: BulletproofABAP

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

Assertions in Productive Systems

Example

Problem evaluating the assertion might be expensive

⇒ not feasible in productive system

METHOD sort_by_name.

the_sorting_algorithm. complicated_stuff.

ASSERT itab->is_sorted_by_name( )

= abap_true.

ENDMETHOD.

Page 108: BulletproofABAP

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

Assertions in Productive Systems

Solutionevaluate expensive assertions only during development, testing and maintenancein 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.

Page 109: BulletproofABAP

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

Assertions That Can be Activated

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

ASSERT

ID <group>

CONDITION <log_expr>.

Page 110: BulletproofABAP

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

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

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

Checkpoint Groups

Transaction

SAAB

Page 111: BulletproofABAP

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

Activation Settings: Overview

An activation setting consists of three componentsScope: To which ASSERT statements does it apply?Target: For which sessions is it effective?Mode: What will happen when the assertion is violated?

An activatable ASSERT statement is ignored

unless an activation setting with matching scope and target specification

is found.

Checkpoint Group User Server Mode

AAB_DEMO TESTUSER * ABORT

Page 112: BulletproofABAP

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

Activation Settings: Scope

A setting only applies to those ASSERT statements which are linked to the specified checkpoint group

Checkpoint Group User Server Mode

AAB_DEMO TESTUSER * ABORT

ASSERT ID some_other_group

CONDITION num < 100.

ASSERT ID aab_demo

CONDITION is_sorted( ) = abap_true.

Page 113: BulletproofABAP

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

Activation Settings: Target

All target settings are client dependent (as of 7.00)

Checkpoint Group User Server Mode

AAB_DEMO TESTUSER * ABORT

User Server* *

All users on all servers: Global activation

User Server* pwdf0195

User ServerTESTUSER *

All users on specified server:Server specific activation

Specified user on all servers: User specific activationSpecial case: Personal activation

Page 114: BulletproofABAP

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

Activation Settings: Mode

What will happen when the assertion is violated?ABORT Runtime error ASSERTION_FAILEDBREAK 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 loggedINACTIVE 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.

Checkpoint Group User Server Mode

AAB_DEMO TESTUSER * ABORT

Page 115: BulletproofABAP

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

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

Page 116: BulletproofABAP

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

Multiple Activation Settings

Checkpoint Group User Server Mode

AAB_DEMO * * ABORT

AAB_DEMO * SERVER1 LOG

AAB_DEMO * SERVER2 BREAK

AAB_DEMO TESTUSER 1 * 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

Page 117: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 117

Multiple Activation Settings: Precedence Rule

Checkpoint Group

User Server Mode

AAB_DEMO * * ABORT

AAB_DEMO * SERVER 1 LOG

AAB_DEMO * SERVER 2 BREAK

AAB_DEMO USER1 * LOG

USER2on

SERVER3

USER2on

SERVER1

USER2on

SERVER2USER1on

SERVER2

User specific setting supersedes

server specific setting supersedes

global setting

Page 118: BulletproofABAP

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

DEMO

Page 119: BulletproofABAP

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

Maintaining Settings: Personal Activation

Set personal activation

here

Transaction

SAAB

Page 120: BulletproofABAP

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

Maintaining Settings: User/Server Specific Activation

Transaction

SAAB

Break Break/Log Break/Abort Abort

Server-specific Settings

User-specific Settings

Page 121: BulletproofABAP

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

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

Page 122: BulletproofABAP

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

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

Page 123: BulletproofABAP

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

Assertion Log: Subkey

To conserve space, we use

aggregationLog entries are aggregated for same ASSERT statementInformation is only available for last violated assertion

Addition SUBKEY to reduce aggregation

Log entries are aggregated for same ASSERT statement with the same subkeyvalue

ASSERT ID

group

SUBKEY

subkey

CONDITION

cond

Page 124: BulletproofABAP

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

Assertion Log: Fields

Default log informationCheckpoint groupSource position: program, include, line number, procedureViolation count (aggregation)Date and time of last violation

Addition FIELDS for additional information

names and values of fields f1 … fn are stored in the logwhen running in ABORT mode, field names and values are listed in runtime error ASSERTION_FAILED

ASSERT ID

group

FIELDS

f1 …

fn

CONDITION

cond

Page 125: BulletproofABAP

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

Activation Variants

Reusing (complex) activation settingsWhen working with a set of checkpoint groups, you may want to store your complex settingsYou may want to transport the stored settingsIn 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.

Page 126: BulletproofABAP

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

Maintaining Activation Variants

Transaction

SAAB

List of checkpoint groups (scope specification)

Corresponding modes

Page 127: BulletproofABAP

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

Variant Activation

Activation target

is specified when activation variant is activated.

Variant is expanded

and setting is applied for each contained checkpoint group.

Transaction

SAAB

Page 128: BulletproofABAP

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

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

Page 129: BulletproofABAP

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

Scope Definition by Compilation Unit: Example

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

application

report x class y function group z

ASSERT ID A

ASSERT ID B

ASSERT ID C

ASSERT ID D

ASSERT ID E

ASSERT ID A

ASSERT ID F

ASSERT ID A

ASSERT ID E

Page 130: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 130

Specifying Settings for a Compilation Unit

Settings for

compilation units

can only be specified using activation variants

Transaction

SAAB

Compilation units

Transaction

SAAB

Page 131: BulletproofABAP

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

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

Page 132: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 132

Fuel your Career with SAP Certification

Take advantage of the enhanced, expanded and multi tier certifications from SAP today!

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 that’s what matters most to customers.”*Conny

Dahlgren, SAP Certified Professional

Page 133: BulletproofABAP

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

Thank you!

Page 134: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 134

Please complete your session evaluation.Be courteous —

deposit your trash,

and do not take the handouts for the following session.

Thank You !

Feedback

Page 135: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 135

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 updatesContinuous learning presentations and demos to build expertise in each of the SAP NetWeaver platform componentsA personal SAP namespace

SAP NetWeaver Content Subscription:

(available globally)An online library of continuous learning content to help build skills.

Starter Kit

Building Your Business with SDN Subscriptions

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

Page 136: BulletproofABAP

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 136

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 Vervielfältigung

dieser

Publikation

oder

von Teilen

daraus

sind, zu

welchem

Zweck

und in welcher

Form auch

immer, ohne

die ausdrückliche

schriftliche

Genehmigung

durch

SAP AG nicht

gestattet. In dieser

Publikation

enthaltene

Informationen

können

ohne

vorherige

Ankündigung

geändert

werden.

Einige

von der

SAP AG und deren

Vertriebspartnern

vertriebene

Softwareprodukte

können

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

erwähnte

SAP-Produkte

und Services sowie

die dazugehörigen

Logos sind

Marken

oder

eingetragene

Marken

der

SAP AG in Deutschland und in mehreren

anderen

Ländern

weltweit. Alle

anderen

in diesem

Dokument

erwähnten

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

können

länderspezifische

Unterschiede

aufweisen.

Die in dieser

Publikation

enthaltene

Information ist

Eigentum

der

SAP. Weitergabe

und Vervielfältigung

dieser

Publikation

oder

von Teilen

daraus

sind, zu

welchem

Zweck

und in welcher

Form auch

immer, nur

mit

ausdrücklicher

schriftlicher

Genehmigung

durch

SAP AG gestattet. Bei

dieser

Publikation

handelt

es

sich

um eine

vorläufige

Version, die nicht

Ihrem

gültigen

Lizenzvertrag

oder

anderen

Vereinbarungen

mit

SAP unterliegt. Diese

Publikation

enthält

nur

vorgesehene

Strategien, Entwicklungen

und Funktionen

des SAP®-Produkts. SAP entsteht

aus

dieser

Publikation

keine

Verpflichtung

zu

einer

bestimmten

Geschäfts-

oder

Produktstrategie

und/oder

bestimmten

Entwicklungen. Diese

Publikation

kann

von SAP jederzeit

ohne

vorherige

Ankündigung

geändert

werden.

SAP übernimmt

keine

Haftung

für

Fehler

oder

Auslassungen

in dieser

Publikation. Des Weiteren

übernimmt

SAP keine

Garantie

für

die Exaktheit

oder

Vollständigkeit

der

Informationen, Texte, Grafiken, Links und sonstigen

in dieser

Publikation

enthaltenen

Elementen. Diese

Publikation

wird

ohne

jegliche

Gewähr, weder

ausdrücklich

noch

stillschweigend, bereitgestellt. Dies gilt u. a., aber

nicht

ausschließlich, hinsichtlich

der

Gewährleistung

der

Marktgängigkeit

und der

Eignung

für

einen

bestimmten

Zweck

sowie

für

die Gewährleistung

der

Nichtverletzung

geltenden

Rechts. SAP haftet

nicht

für

entstandene

Schäden. Dies gilt u.

a. und uneingeschränkt

für

konkrete, besondere

und mittelbare

Schäden

oder

Folgeschäden, die aus

der

Nutzung

dieser

Materialien

entstehen

können. Diese

Einschränkung

gilt nicht

bei

Vorsatz

oder

grober

Fahrlässigkeit.

Die gesetzliche

Haftung

bei

Personenschäden

oder

Produkthaftung

bleibt

unberührt. Die Informationen, auf die Sie

möglicherweise

über

die in diesem

Material enthaltenen

Hotlinks zugreifen, unterliegen

nicht

dem

Einfluss

von SAP, und SAP unterstützt

nicht

die Nutzung

von Internetseiten

Dritter

durch

Sie

und gibt

keinerlei

Gewährleistungen

oder

Zusagen

über

Internetseiten

Dritter

ab.

Alle

Rechte

vorbehalten.


Recommended