Beyond ABAPdesigned by@Tejoram97
Beyond ABAP / OOPS ABAP / Exceptions, Events & Advanced OO

Exceptions, Events & Advanced OO

OOPS ABAP · ABAP Development ·

Open the interactive lesson →
  1. Class-based exceptions: TRY, CATCH, CLEANUP
  2. Exception categories and RAISING
  3. Raising exceptions
  4. Custom exception classes with message texts
  5. RESUMABLE, RESUME and RETRY
  6. Events
  7. RTTS: RTTI and RTTC
  8. More runtime services: serialisation, weak references, shared objects
  9. Design patterns
  10. SOLID and Clean ABAP
  11. ABAP Unit, injection and test doubles
  12. OO in ABAP Cloud and S/4HANA
  13. OO transactions (SE93)
  14. Legacy: persistence service and transaction service
  15. Interview questions

The advanced half of ABAP Objects: how errors travel through your code (class-based exceptions), how objects notify each other (events), how a program inspects and builds types at runtime (RTTS), and the patterns and tests that keep OO code clean, and what changes for OO code in ABAP Cloud and S/4HANA. Pages 01 and 02 are the basis; the persistence and transaction services at the end are Legacy – know them for interviews, use RAP for new code.

Page at a glance

Mind map of this page: exceptions, texts and RESUME/RETRY, events, runtime services, design, testing, ABAP Cloud and legacy techniques around the idea 'robust, decoupled, testable'

Part 1 – Class-based exceptions: TRY, CATCH, CLEANUP

An exception is an error situation signalled while the program runs (division by zero, missing table line, flight not found). The runtime creates an exception object – an instance of a class whose name starts with CX_ (SAP) or ZCX_ (yours) – and looks for a handler. Only an exception that nobody handles becomes a runtime error (short dump, ST22).

  • Exceptions raised by SAP (e.g. CX_SY_ZERODIVIDE) are declared and raised by the kernel or by SAP classes; you only handle them. Your own exceptions (ZCX_…) you declare, raise and handle yourself.
  • TRY encloses the statements that might raise. When an exception occurs, the rest of the TRY block is skipped and control jumps to a matching CATCH.
  • CATCH cx_a cx_b INTO DATA(lx) – one CATCH may list several classes; INTO gives you the object, so you can call lx->get_text( ), lx->get_longtext( ), lx->get_source_position( ) or read lx->previous.
  • A CATCH for a class also catches all its subclasses. Order CATCH blocks from most specific (subclass) to most general (superclass) – the reverse order is a syntax error, because the later block could never be reached.
  • Catching CX_ROOT is allowed but bad practice: it also swallows programming errors you should fix. Catch the specific class, or the category class at most.
DATA(lv_total) = 100.
DATA(lv_count) = 0.
TRY.
DATA(lv_avg) = lv_total / lv_count.              "raises CX_SY_ZERODIVIDE
WRITE: / 'Average:', lv_avg.                     "skipped
CATCH cx_sy_zerodivide INTO DATA(lx_zero).
WRITE: / 'Error:', lx_zero->get_text( ).
CATCH cx_sy_arithmetic_error INTO DATA(lx_arith).  "superclass: must come after
WRITE: / 'Arithmetic error:', lx_arith->get_text( ).
ENDTRY.
WRITE: / 'Program continues'.

CLEANUP – tidy up before the exception moves on

A TRY block can have CATCH blocks and one CLEANUP block (after the CATCHes). CLEANUP runs only when an exception raised in this TRY is not caught here but by an outer handler (an enclosing TRY or a calling method). Use it to restore a consistent state: clear variables, free tables, close files, release locks. CLEANUP INTO lx gives you the exception object.

Which block runs: no exception, caught by the inner CATCH, CLEANUP then outer CATCH, nobody catches it
  • CLEANUP must be left normally through ENDTRY so the exception can reach its handler. Statements that leave it early (RETURN, EXIT, CHECK, STOP, LEAVE …, SUBMIT without AND RETURN, LEAVE TO TRANSACTION) are syntax errors or cause a runtime error.
  • If no handler exists anywhere, the program dumps at the point of the error and CLEANUP is not run.
  • ABAP has no FINALLY. Code that must always run goes after ENDTRY (and into CLEANUP for the propagating case).

Common standard exceptions

Exception class

Raised when

CX_SY_ZERODIVIDE

Division by zero

CX_SY_ARITHMETIC_OVERFLOW

Result too large for the target type

CX_SY_CONVERSION_NO_NUMBER

Text like 'ABC' converted to a number

CX_SY_ITAB_LINE_NOT_FOUND

Table expression itab[ … ] finds no line

CX_SY_REF_IS_INITIAL

Method call or ->* on an unbound reference

CX_SY_MOVE_CAST_ERROR

Down cast ?= / CAST to the wrong class

CX_SY_OPEN_SQL_DB

Database error in ABAP SQL (e.g. duplicate key in INSERT … FROM TABLE)

CX_SY_DYNAMIC_OSQL_SEMANTICS

Wrong table or field name in dynamic ABAP SQL

CX_SY_NO_HANDLER

A checked exception left a method without being declared (Part 2)

Part 2 – Exception categories and RAISING

Every exception class inherits from CX_ROOT through exactly one of three abstract category classes. The category decides whether a method must declare the exception and when this is checked.

CX_ROOT with CX_STATIC_CHECK, CX_DYNAMIC_CHECK and CX_NO_CHECK

CX_STATIC_CHECK

CX_DYNAMIC_CHECK

CX_NO_CHECK

Use for

Errors every caller must expect (application errors)

Errors the caller can avoid by checking preconditions

Errors that usually can't be handled locally

Declare in RAISING?

Must (if not handled in the method)

Should

Never needed – implicitly declared

Checked

Compile time: syntax check warning

Runtime: when it leaves a method

Not checked

Examples

Most custom ZCX_…

CX_SY_ZERODIVIDE, CX_SY_ITAB_LINE_NOT_FOUND

CX_SY_EXPORT_BUFFER_NO_MEMORY

RAISING – the exception belongs to the caller

RAISING in a method signature says: this exception may leave the method and propagates to the caller, who handles it (or declares it again). Advantage: each caller reacts in its own way – one shows a message, another logs and continues.

CLASS lcl_flight_reader DEFINITION.
PUBLIC SECTION.
METHODS get_price
IMPORTING iv_carrid       TYPE s_carr_id
iv_connid       TYPE s_conn_id
RETURNING VALUE(rv_price) TYPE s_price
RAISING   zcx_demo_flight.  "caller must handle it
ENDCLASS.

TRY.
DATA(lv_price) = NEW lcl_flight_reader( )->get_price( iv_carrid = 'LH'
iv_connid = '0400' ).
CATCH zcx_demo_flight INTO DATA(lx_flight).
MESSAGE lx_flight TYPE 'I' DISPLAY LIKE 'E'.
ENDTRY.
  • If a STATIC or DYNAMIC exception leaves a method without a RAISING declaration, the runtime raises CX_SY_NO_HANDLER instead (catchable; the original exception is in its previous attribute).
  • The signature order is IMPORTING, EXPORTING, CHANGING, RETURNING, then RAISING (or EXCEPTIONS).
  • An exception raised in an instance constructor means the object is not created – the reference keeps its previous value.
  • Exceptions vs ASSERT: exceptions are for error situations that can really happen; ASSERT is for conditions that must never be false (a bug) and dumps with ASSERTION_FAILED.

Part 3 – Raising exceptions

Syntax

Since

Use

RAISE EXCEPTION TYPE zcx_x EXPORTING textid = … previous = …

6.10

Classic form, still common

RAISE EXCEPTION NEW zcx_x( … )

7.52

Same, with the NEW operator

RAISE EXCEPTION lx

6.10

Re-raise an existing exception object

THROW zcx_x( … ) inside COND / SWITCH

7.40

Raise inside an expression

RAISE EXCEPTION TYPE zcx_x MESSAGE e001(zmsg) WITH v1 v2

7.50

Text from a message class (Part 4)

RAISE RESUMABLE EXCEPTION TYPE zcx_x

7.02

Caller may continue after RAISE (Part 5)

RAISE SHORTDUMP TYPE zcx_x / THROW SHORTDUMP zcx_x( )

7.53

Runtime error with an exception object – cannot be caught (below)

METHOD get_price.
SELECT SINGLE price FROM sflight
WHERE carrid = @iv_carrid AND connid = @iv_connid
INTO @rv_price.
IF sy-subrc <> 0.
RAISE EXCEPTION NEW zcx_demo_flight( textid = zcx_demo_flight=>flight_not_found
carrid = iv_carrid
connid = iv_connid ).
ENDIF.
ENDMETHOD.

" THROW inside an expression
rv_price = COND #( WHEN line_exists( mt_prices[ carrid = iv_carrid ] )
THEN mt_prices[ carrid = iv_carrid ]-price
ELSE THROW zcx_demo_flight( carrid = iv_carrid ) ).

" Exception chaining: wrap a technical error, keep the original in PREVIOUS
TRY.
INSERT zdemo_booking FROM TABLE @lt_bookings.
CATCH cx_sy_open_sql_db INTO DATA(lx_sql).
RAISE EXCEPTION NEW zcx_demo_flight( previous = lx_sql ).
ENDTRY.

Exception chaining – wrap, don't leak

A layer that calls technical code catches the technical exception and raises its own exception with previous = lx. Callers then handle one exception class of your API, and the original cause is still available for logging.

Exception chaining: the database raises CX_SY_OPEN_SQL_DB, the service class raises ZCX_DEMO_FLIGHT with previous = lx_sql, the caller shows get_text( ) and walks the previous chain
" Log every level of the chain
DATA(lx_level) = CAST cx_root( lx_flight ).
WHILE lx_level IS BOUND.
APPEND lx_level->get_text( ) TO lt_log.
lx_level = lx_level->previous.
ENDWHILE.

RAISE SHORTDUMP – stop on purpose, with a clear reason (7.53)

Some states are unrecoverable: a mandatory configuration is missing, an internal invariant is broken. RAISE SHORTDUMP ends the program with a runtime error, like an unhandled exception, but on purpose: the short dump (ST22) shows the exception class and its text. It cannot be caught – no TRY block can stop it.

IF ls_config IS INITIAL.
RAISE SHORTDUMP TYPE zcx_demo_config_missing.  "dump with class and text in ST22
ENDIF.

" Inside an expression
rv_rate = COND #( WHEN iv_currency = 'EUR' THEN 1
ELSE THROW SHORTDUMP zcx_demo_config_missing( ) ).
  • Like any runtime error it ends the program and rolls back the open database changes. Text and attributes come from the exception class, so you can use the same message class texts as for normal exceptions.

Tool

Use it for

Caller can react?

Exception (RAISE EXCEPTION)

Errors that can really happen and that some caller can handle

Yes – CATCH

ASSERT condition

A condition that must be true unless there is a bug; dump ASSERTION_FAILED, no own text (checkpoint groups can switch it to a log entry)

No

RAISE SHORTDUMP

Unrecoverable state where a dump with a precise class and text helps the analysis

No

MESSAGE … TYPE 'X'

Older way to force a dump (MESSAGE_TYPE_X); no exception object

No

  • Clean ABAP: "Dump for totally unrecoverable situations" – everything else is an exception.

Legacy – classic (non-class-based) exceptions

Older methods and almost all function modules use classic exceptions: declared with EXCEPTIONS, raised with RAISE name (or MESSAGE … RAISING name), handled by checking SY-SUBRC. Know them to call old code; use class-based exceptions in new methods.

METHODS divide IMPORTING iv_a TYPE i iv_b TYPE i
EXPORTING ev_result TYPE i
EXCEPTIONS division_by_zero.

METHOD divide.
IF iv_b = 0.
RAISE division_by_zero.  "classic: no object, only sy-subrc
ENDIF.
ev_result = iv_a / iv_b.
ENDMETHOD.

lo_calc->divide( EXPORTING iv_a = 10 iv_b = 0
IMPORTING ev_result = DATA(lv_result)
EXCEPTIONS division_by_zero = 1 OTHERS = 2 ).
IF sy-subrc <> 0.
WRITE: / 'Division failed'.
ENDIF.
  • One method cannot use both EXCEPTIONS and RAISING.
  • RAISE name raises only classic exceptions; class-based exceptions always need RAISE EXCEPTION or THROW.

Part 4 – Custom exception classes with message texts

A global exception class is created in SE24 or ADT, named ZCX_…, and inherits from CX_STATIC_CHECK, CX_DYNAMIC_CHECK or CX_NO_CHECK (or from another exception class). It is a repository of related error texts; each text has an exception ID – a constant attribute you pass as textid when raising.

  • With message class (recommended): tick "With message class" – the class implements IF_T100_MESSAGE. Each exception ID points to a message of a message class (SE91 or the ADT message class editor).
    • The ID constant is a structure of type SCX_T100KEY: MSGID, MSGNO and ATTR1–ATTR4. ATTR1–4 name the class attributes that fill the placeholders &1–&4 of the message.
    • Fill those attributes when raising (constructor parameters with the same names).
  • IF_T100_DYN_MSG (7.50): lets you raise with any message directly – RAISE EXCEPTION TYPE zcx_x MESSAGE e001(zmsg) WITH v1 v2 – and display it with MESSAGE lx TYPE 'E'. Preferred in new code; ADT's exception class template uses it.
  • Legacy – OTR texts: the old "Texts" tab with short/long texts from the Online Text Repository. Still found in older classes; not available in ABAP Cloud – use message classes.
" Message ZDEMO_FLIGHT 001: 'Flight &1 &2 does not exist'
CLASS zcx_demo_flight DEFINITION PUBLIC INHERITING FROM cx_static_check FINAL CREATE PUBLIC.
PUBLIC SECTION.
INTERFACES if_t100_dyn_msg.  "includes IF_T100_MESSAGE
CONSTANTS:
BEGIN OF flight_not_found,
msgid TYPE symsgid      VALUE 'ZDEMO_FLIGHT',
msgno TYPE symsgno      VALUE '001',
attr1 TYPE scx_attrname VALUE 'CARRID',
attr2 TYPE scx_attrname VALUE 'CONNID',
attr3 TYPE scx_attrname VALUE '',
attr4 TYPE scx_attrname VALUE '',
END OF flight_not_found.
DATA carrid TYPE s_carr_id READ-ONLY.
DATA connid TYPE s_conn_id READ-ONLY.
METHODS constructor
IMPORTING textid   LIKE if_t100_message=>t100key OPTIONAL
previous LIKE previous OPTIONAL
carrid   TYPE s_carr_id OPTIONAL
connid   TYPE s_conn_id OPTIONAL.
ENDCLASS.

CLASS zcx_demo_flight IMPLEMENTATION.
METHOD constructor ##ADT_SUPPRESS_GENERATION.
super->constructor( previous = previous ).
me->carrid = carrid.
me->connid = connid.
CLEAR me->textid.
IF textid IS INITIAL.
if_t100_message~t100key = if_t100_message=>default_textid.
ELSE.
if_t100_message~t100key = textid.
ENDIF.
ENDMETHOD.
ENDCLASS.

" Raising – two ways
RAISE EXCEPTION TYPE zcx_demo_flight
EXPORTING textid = zcx_demo_flight=>flight_not_found carrid = 'LH' connid = '0400'.
RAISE EXCEPTION TYPE zcx_demo_flight MESSAGE e001(zdemo_flight) WITH 'LH' '0400'.
Where the text comes from: exception ID constant (MSGID, MSGNO, ATTR1-ATTR2) plus attributes CARRID/CONNID fill message ZDEMO_FLIGHT 001; or the MESSAGE addition stores MSGTY and MSGV1-MSGV4 in IF_T100_DYN_MSG

Errors in RAP: failed and reported instead of RAISE

In a RAP behaviour handler (Part 12) the RAP runtime is your caller, so you don't raise exceptions to it. You report problems in the response parameters and let RAP decide what happens to the transaction.

  • failed – which instances failed (%tky, optionally %fail-cause).
  • reported – the messages for the UI in %msg, an object of type IF_ABAP_BEHV_MESSAGE. Create it with the inherited methods new_message( … ) / new_message_with_text( … ), or with your own exception class that implements IF_ABAP_BEHV_MESSAGE – then one ZCX class serves classic code and RAP.
  • Don't let exceptions leave a handler method: catch them and turn them into failed / reported entries. Code example in Part 12; details in RAP › 05 · Business Logic & Messages.

Part 5 – RESUMABLE, RESUME and RETRY

Feature

What it does

Syntax

Resumable exception

The handler may let the raising method continue after the RAISE statement (like a warning)

RAISING RESUMABLE(zcx_x) in every signature on the way; RAISE RESUMABLE EXCEPTION TYPE zcx_x

CATCH BEFORE UNWIND

Handler runs before the call stack is cleared – needed for RESUME

CATCH BEFORE UNWIND zcx_x INTO lx

RESUME

Continue directly after the RAISE in the method

IF lx->is_resumable = abap_true. RESUME. ENDIF.

RETRY (7.02)

Restart the whole TRY block after fixing the cause

RETRY. inside a CATCH block

RESUME continues in the method right after RAISE RESUMABLE (CATCH BEFORE UNWIND, stack not unwound); RETRY restarts the TRY block after the handler fixed the cause
METHODS check_amount IMPORTING iv_amount TYPE i RAISING RESUMABLE(zcx_demo_warning).

METHOD check_amount.
IF iv_amount > 10000.
RAISE RESUMABLE EXCEPTION TYPE zcx_demo_warning.
ENDIF.
WRITE: / 'Amount accepted'.  "reached after RESUME
ENDMETHOD.

TRY.
lo_check->check_amount( 20000 ).
CATCH BEFORE UNWIND zcx_demo_warning INTO DATA(lx_warn).
IF lx_warn->is_resumable = abap_true.
RESUME.  "back into check_amount
ENDIF.
ENDTRY.

" RETRY: fix the cause, then run the TRY block again
DATA(lv_div) = 0.
TRY.
DATA(lv_res) = 100 / lv_div.
CATCH cx_sy_zerodivide.
lv_div = 1.  "without a fix RETRY loops forever
RETRY.
ENDTRY.

Part 6 – Events

An event lets an object announce "something happened" without knowing who reacts. The sender raises the event; any number of handler methods in the same or other classes react – but only if they were registered with SET HANDLER. This is ABAP's built-in observer pattern and the way ALV grids report clicks to your program.

Events: declare, handler method, SET HANDLER, RAISE EVENT and the handler table

The four steps

  • 1. Declare in the sender class (or an interface): EVENTS name EXPORTING VALUE(p) TYPE t. (instance) or CLASS-EVENTS (static). Only the declaration part of a class or interface can contain events.
  • 2. Handler method in the same or another class: METHODS h FOR EVENT name OF lcl_sender IMPORTING p sender. (or CLASS-METHODS for a static handler).
  • 3. Register before the event is raised: SET HANDLER lo_handler->h FOR lo_sender. – the reference before -> is the handler object, the reference after FOR is the sender.
  • 4. Raise inside a method of the sender class: RAISE EVENT name EXPORTING p = value.
CLASS lcl_account DEFINITION.
PUBLIC SECTION.
EVENTS overdrawn EXPORTING VALUE(ev_balance) TYPE i.
METHODS withdraw IMPORTING iv_amount TYPE i.
PRIVATE SECTION.
DATA mv_balance TYPE i VALUE 100.
ENDCLASS.

CLASS lcl_account IMPLEMENTATION.
METHOD withdraw.
mv_balance = mv_balance - iv_amount.
IF mv_balance < 0.
RAISE EVENT overdrawn EXPORTING ev_balance = mv_balance.
ENDIF.
ENDMETHOD.
ENDCLASS.

CLASS lcl_alerter DEFINITION.
PUBLIC SECTION.
METHODS on_overdrawn FOR EVENT overdrawn OF lcl_account
IMPORTING ev_balance sender.
ENDCLASS.

CLASS lcl_alerter IMPLEMENTATION.
METHOD on_overdrawn.
WRITE: / |Account overdrawn, balance { ev_balance }|.
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
DATA(lo_account) = NEW lcl_account( ).
DATA(lo_alerter) = NEW lcl_alerter( ).
SET HANDLER lo_alerter->on_overdrawn FOR lo_account.  "register first
lo_account->withdraw( 150 ).                          "handler runs
SET HANDLER lo_alerter->on_overdrawn FOR lo_account ACTIVATION abap_false.
lo_account->withdraw( 10 ).                           "deregistered: nothing happens

Rules

  • Handlers are never called directly; without a registration (or with one made after the RAISE) nothing happens – no error either. Registered FOR lo_b but lo_a raises → the handler does not run either.
  • Static handler (CLASS-METHODS … FOR EVENT): register it with the class name – SET HANDLER lcl_log=>on_overdrawn FOR lo_account. (instance event) or SET HANDLER lcl_log=>on_static_evt. (static event, no FOR).
  • Event parameters are EXPORTING only and always passed by value; the handler imports them under the same names. Mandatory parameters must be supplied in RAISE EVENT.
  • Every instance event has the implicit parameter SENDER – a reference to the raising object. Import it when one handler serves many senders.
  • Handler visibility rule: the visibility section of the handler method cannot be more general than that of the event (SAP keyword documentation). A PRIVATE handler for a PUBLIC event is fine; a PUBLIC handler for a PRIVATE event is a syntax error. The handler's visibility also decides who may register it with SET HANDLER.
  • Handler IMPORTING lists only names – no TYPE/LIKE, OPTIONAL or DEFAULT (the types come from the event), and it may import just some of the event's parameters.
  • When an event has several handlers, they run one after another (in practice in registration order – don't build logic on the order). Control returns to the statement after RAISE EVENT.
  • ACTIVATION 'X' (the default) registers, ACTIVATION abap_false (space) deregisters.
  • Registered handlers stay alive: while an instance handler is registered for an instance event, the runtime still uses the handler object, so the garbage collector does not delete it – even if your program has no reference to it any more. It becomes collectable only after deregistration (ACTIVATION abap_false) or when all raising objects are gone. Deregister handlers you no longer need in long-running programs.

Instance event

Static event

Declared with

EVENTS

CLASS-EVENTS

Raised in

Instance methods of the class only

Instance or static methods of the class

Implicit SENDER

Yes

No

Registration

SET HANDLER h FOR lo_sender or FOR ALL INSTANCES (also objects created later)

SET HANDLER h – no FOR addition

Handler method

Instance or static

Instance or static

  • Visibility: the event's section decides where handlers can be declared – public: anywhere; protected: the class and its subclasses; private: only the class itself (private events are not visible in subclasses). SET HANDLER can be written wherever the handler method is visible.
  • Events in interfaces: EVENTS e in INTERFACE zif_x; the implementing class raises RAISE EVENT zif_x~e; handlers are declared FOR EVENT e OF zif_x and react to every implementing class.
  • Standard events: SAP classes raise events, you only handle them – e.g. CL_SALV_TABLE (get_event( ) → double_click, link_click, added_function) and CL_GUI_ALV_GRID (double_click, hotspot_click, toolbar, user_command, data_changed). See page 04 ALV Reporting.
  • RAP business events are the RAP counterpart: declared in the behaviour definition, raised with RAISE ENTITY EVENT during the save sequence (saver class, Part 12) and consumed decoupled from the sender. See RAP › 10 · Business Events & Event-Driven RAP.

Part 7 – RTTS: RTTI and RTTC

RTTS (Run Time Type Services) describes and creates types while the program runs. It has two parts:

  • RTTI (Run Time Type Identification): read the definition of a type, variable or object – the describe_… methods.
  • RTTC (Run Time Type Creation): build new types dynamically – the get( ) / create( ) methods – and create data objects with CREATE DATA … TYPE HANDLE.
RTTS inheritance tree: CL_ABAP_TYPEDESCR, DATADESCR, ELEMDESCR, ENUMDESCR, REFDESCR, COMPLEXDESCR, STRUCTDESCR, TABLEDESCR, OBJECTDESCR, CLASSDESCR, INTFDESCR (abstract vs concrete)
  • CL_ABAP_ENUMDESCR (enumerated types, 7.51) is a subclass of ELEMDESCR.

RTTI method

Gives you

cl_abap_typedescr=>describe_by_name( 'SFLIGHT' )

Description of a DDIC or program type by name

cl_abap_typedescr=>describe_by_data( lv_x )

Description of a variable's type

cl_abap_typedescr=>describe_by_data_ref( lr_x )

Type of the data a reference points to

cl_abap_typedescr=>describe_by_object_ref( lo_x )

Class of an object → get_relative_name( ), methods, attributes

lo_struct->components / get_components( )

Fields of a structure

lo_struct->get_ddic_field_list( )

DDIC field info incl. texts

CAST cl_abap_classdescr( cl_abap_typedescr=>describe_by_name( 'ZCL_X' ) )

A class: methods, attributes, interfaces, get_super_class_type( ); applies_to( lo_obj ) tells whether an object fits this type

" RTTI: list the fields of SFLIGHT
DATA(lo_struct) = CAST cl_abap_structdescr( cl_abap_typedescr=>describe_by_name( 'SFLIGHT' ) ).
LOOP AT lo_struct->components INTO DATA(ls_comp).
WRITE: / ls_comp-name, ls_comp-type_kind, ls_comp-length.
ENDLOOP.

" RTTC: build a structure and table type at runtime, then create the table
DATA(lo_row) = cl_abap_structdescr=>get( VALUE #(
( name = 'CARRID'
type = CAST cl_abap_datadescr( cl_abap_typedescr=>describe_by_name( 'S_CARR_ID' ) ) )
( name = 'PRICE'  type = cl_abap_elemdescr=>get_p( p_length = 8 p_decimals = 2 ) ) ) ).
DATA(lo_tab_type) = cl_abap_tabledescr=>get( lo_row ).
DATA lr_table TYPE REF TO data.
CREATE DATA lr_table TYPE HANDLE lo_tab_type.
  • CREATE DATA … TYPE HANDLE needs a data reference (TYPE REF TO data) and a handle whose static type is CL_ABAP_DATADESCR or a subclass (struct, table, elem, ref descr). cl_abap_tabledescr=>create( line_type ) returns the table description object.

Example: display any allowed table dynamically (safe version)

The classic RTTS exercise: the user enters a table name, the program builds a matching internal table and shows its rows. Reading any table the user types would be a serious security hole (it bypasses table authorizations). This version validates the name against an allow-list and runs an authority check before reading.

REPORT zrtts_demo_dynamic_table.

TYPES tt_tabname TYPE STANDARD TABLE OF tabname WITH EMPTY KEY.
PARAMETERS p_tab TYPE tabname DEFAULT 'SFLIGHT'.

FIELD-SYMBOLS: <lt_data>  TYPE STANDARD TABLE,
<ls_row>   TYPE any,
<lv_field> TYPE any.
DATA lr_table TYPE REF TO data.

START-OF-SELECTION.
" 1. Security: only known tables, and only if the user may display them
DATA(lt_allowed) = VALUE tt_tabname( ( 'SFLIGHT' ) ( 'SCARR' ) ( 'SPFLI' ) ).
IF NOT line_exists( lt_allowed[ table_line = p_tab ] ).
MESSAGE |Table { p_tab } is not allowed| TYPE 'E'.
ENDIF.
CALL FUNCTION 'VIEW_AUTHORITY_CHECK'  "checks S_TABU_DIS / S_TABU_NAM
EXPORTING  view_action = 'S'
view_name   = p_tab
EXCEPTIONS OTHERS      = 1.
IF sy-subrc <> 0.
MESSAGE |No authorization to display { p_tab }| TYPE 'E'.
ENDIF.

" 2. RTTS: row type -> table type -> data object
TRY.
DATA(lo_row)  = CAST cl_abap_structdescr( cl_abap_typedescr=>describe_by_name( p_tab ) ).
DATA(lo_type) = cl_abap_tabledescr=>create( lo_row ).
CREATE DATA lr_table TYPE HANDLE lo_type.
CATCH cx_sy_table_creation cx_sy_move_cast_error INTO DATA(lx_rtts).
MESSAGE lx_rtts TYPE 'E'.
ENDTRY.
ASSIGN lr_table->* TO <lt_data>.

" 3. Read and print field by field
SELECT * FROM (p_tab) INTO TABLE @<lt_data> UP TO 8 ROWS.
LOOP AT <lt_data> ASSIGNING <ls_row>.
DO.
ASSIGN COMPONENT sy-index OF STRUCTURE <ls_row> TO <lv_field>.
IF sy-subrc <> 0.
EXIT.
ENDIF.
WRITE <lv_field>.
ENDDO.
NEW-LINE.
ENDLOOP.
  • Shortcut without RTTS: CREATE DATA lr_table TYPE STANDARD TABLE OF (p_tab). – the same result in one line. RTTS is needed when you build types that exist nowhere in the dictionary.
  • describe_by_name raises the classic exception TYPE_NOT_FOUND for an unknown name – a functional call can't catch it and dumps. The allow-list prevents that; otherwise call it with EXCEPTIONS type_not_found = 1.
  • For free-text names use CL_ABAP_DYN_PRG (e.g. check_table_name_str) to validate, never concatenate user input into dynamic SQL. CL_ABAP_TABLEDESCR=>GET is the cached alternative to CREATE.

Part 8 – More runtime services: serialisation, weak references, shared objects

Three services of the ABAP runtime that change how long an object lives and where it can go: into a string (serialisation), out of memory when nobody needs it (weak references), or into memory shared by many sessions (shared objects).

Serialising objects (asXML)

Serialising turns an object into a string you can store or send; deserialising builds a new object with the same state from it. CALL TRANSFORMATION id does both, using SAP's canonical XML format asXML.

  • The class must implement the tag interface IF_SERIALIZABLE_OBJECT (it has no methods). For other classes the object is written without its attributes.
  • By default all instance attributes are written, including private ones; static attributes are not. Referenced objects are serialised with it, so a whole object graph can travel.
  • To control the output, declare the private instance methods SERIALIZE_HELPER and DESERIALIZE_HELPER; then the attributes of that class part are no longer written automatically.
CLASS lcl_cart DEFINITION.
PUBLIC SECTION.
INTERFACES if_serializable_object.  "tag interface: no methods
METHODS add IMPORTING iv_item TYPE string.
PRIVATE SECTION.
DATA mt_items TYPE string_table.    "private, but still serialised
ENDCLASS.

CLASS lcl_cart IMPLEMENTATION.
METHOD add.
APPEND iv_item TO mt_items.
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
DATA lv_xml  TYPE xstring.
DATA lo_copy TYPE REF TO lcl_cart.
DATA(lo_cart) = NEW lcl_cart( ).
lo_cart->add( `Book` ).

CALL TRANSFORMATION id SOURCE cart = lo_cart RESULT XML lv_xml.  "object -> asXML
CALL TRANSFORMATION id SOURCE XML lv_xml RESULT cart = lo_copy.  "asXML -> new object
  • Uses: keep object state in a database table or a background job's parameters, or make a deep copy of an object graph.
  • JSON: for data (structures, tables) use CALL TRANSFORMATION id with a JSON writer (cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json )) or xco_cp_json (Part 12). The popular /UI2/CL_JSON is also released for ABAP Cloud.
  • ABAP Cloud: check on your release whether IF_SERIALIZABLE_OBJECT is released before relying on object serialisation there.

Weak references

A normal (strong) reference keeps its object alive. A weak reference – an object of CL_ABAP_WEAK_REFERENCE – points to an object without keeping it alive. When no strong reference is left, the garbage collector may delete the object; get( ) then returns an initial reference.

DATA(lo_buffer) = NEW lcl_big_buffer( ).
DATA(lo_weak)   = NEW cl_abap_weak_reference( lo_buffer ).  "does not keep it alive
CLEAR lo_buffer.                                            "last strong reference gone

DATA(lo_object) = lo_weak->get( ).  "REF TO object: the buffer, or initial if collected
IF lo_object IS BOUND.
lo_buffer = CAST lcl_big_buffer( lo_object ).  "strong again
ELSE.
lo_buffer = NEW #( ).                          "collected: build it again
ENDIF.
  • Use it for caches and registries that must not stop memory from being freed. The runtime decides when the garbage collector runs, so never rely on the moment.
  • CL_ABAP_SOFT_REFERENCE exists as well; it currently behaves like the weak reference.

Shared objects – objects in shared memory

Objects normally live in one internal session. Shared objects live in the shared memory of the application server, so many programs and users read the same object – e.g. a large buffer of rates – without loading it again. The full topic (SHMA, locks, versions, monitor SHMM) is on CORE ABAP › 14; here is the OO view.

  • Area (transaction SHMA): its name is the name of the generated area class, a subclass of CL_SHM_AREA. Its static methods attach_for_write( ) / attach_for_read( ) return an area handle.
  • Root class: an ordinary global class declared with SHARED MEMORY ENABLED; its object is the entry point to the data in the area.
  • Objects in the area are created with CREATE OBJECT … AREA HANDLE – NEW has no such addition.
" Writer: build the object once in shared memory
DATA lo_root TYPE REF TO zcl_demo_rates_root.             "CLASS … SHARED MEMORY ENABLED
DATA(lo_handle) = zcl_demo_rates_area=>attach_for_write( ).
CREATE OBJECT lo_root AREA HANDLE lo_handle.
lo_root->load_rates( ).
lo_handle->set_root( lo_root ).
lo_handle->detach_commit( ).                              "now visible to readers

" Reader: any program on the same application server
DATA(lo_reader) = zcl_demo_rates_area=>attach_for_read( ).
DATA(lv_rate)   = lo_reader->root->get_rate( 'USD' ).
lo_reader->detach( ).
  • Wrap attach calls in TRY … CATCH cx_shm_attach_error (e.g. no active version yet, or locked).
  • A classic on-premise technique; check your release before planning it for ABAP Cloud.

Part 9 – Design patterns

A design pattern is a proven, reusable solution to a recurring design problem. The three you must be able to code or explain in an ABAP interview are singleton, factory and MVC.

Three patterns as mini UML: singleton lcl_logger (FINAL CREATE PRIVATE, go_instance, get_instance), factory returning lif_shipping implemented by lcl_road and lcl_air, and MVC with controller, model and view

Singleton – exactly one instance

CREATE PRIVATE stops everyone else from using NEW; a static method hands out the one instance, stored in a static attribute. Make the class FINAL (a subclass of a CREATE PRIVATE class could not be instantiated anyway). The instance lives once per internal session. Example in SAP: the agent classes of the persistence service (Part 14). Clean ABAP: make singletons only where several instances really make no sense – a singleton is hard to replace in a unit test.

CLASS lcl_logger DEFINITION FINAL CREATE PRIVATE.
PUBLIC SECTION.
CLASS-METHODS get_instance RETURNING VALUE(ro_instance) TYPE REF TO lcl_logger.
METHODS log IMPORTING iv_text TYPE string.
PRIVATE SECTION.
CLASS-DATA go_instance TYPE REF TO lcl_logger.
DATA mt_messages TYPE string_table.
ENDCLASS.

CLASS lcl_logger IMPLEMENTATION.
METHOD get_instance.
IF go_instance IS NOT BOUND.
go_instance = NEW #( ).  "created on first use only
ENDIF.
ro_instance = go_instance.
ENDMETHOD.
METHOD log.
APPEND iv_text TO mt_messages.
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
lcl_logger=>get_instance( )->log( `Started` ).
" DATA(lo_x) = NEW lcl_logger( ).  -> syntax error: CREATE PRIVATE

Factory – hide how objects are created

A factory method decides which class to instantiate and returns it as an interface (or superclass) reference. Callers depend only on the interface; adding a new variant changes the factory, not the callers. SAP's best-known example: CL_SALV_TABLE=>FACTORY.

INTERFACE lif_shipping.
METHODS cost IMPORTING iv_kg TYPE i RETURNING VALUE(rv_cost) TYPE i.
ENDINTERFACE.

CLASS lcl_road DEFINITION.
PUBLIC SECTION.
INTERFACES lif_shipping.
ENDCLASS.
CLASS lcl_road IMPLEMENTATION.
METHOD lif_shipping~cost.
rv_cost = iv_kg * 2.
ENDMETHOD.
ENDCLASS.

CLASS lcl_air DEFINITION.
PUBLIC SECTION.
INTERFACES lif_shipping.
ENDCLASS.
CLASS lcl_air IMPLEMENTATION.
METHOD lif_shipping~cost.
rv_cost = iv_kg * 10.
ENDMETHOD.
ENDCLASS.

CLASS lcl_shipping_factory DEFINITION.
PUBLIC SECTION.
CLASS-METHODS create IMPORTING iv_mode       TYPE string
RETURNING VALUE(ro_ship) TYPE REF TO lif_shipping.
ENDCLASS.
CLASS lcl_shipping_factory IMPLEMENTATION.
METHOD create.
CASE iv_mode.
WHEN `AIR`.
ro_ship = NEW lcl_air( ).
WHEN OTHERS.
ro_ship = NEW lcl_road( ).
ENDCASE.
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
DATA(lo_ship) = lcl_shipping_factory=>create( `AIR` ).
WRITE: / lo_ship->cost( 5 ).  "50

" SAP's factory: the SALV object is created for you
SELECT * FROM sflight INTO TABLE @DATA(lt_flights) UP TO 20 ROWS.
TRY.
cl_salv_table=>factory( IMPORTING r_salv_table = DATA(lo_alv)
CHANGING  t_table      = lt_flights ).
lo_alv->display( ).
CATCH cx_salv_msg INTO DATA(lx_salv).
MESSAGE lx_salv TYPE 'I'.
ENDTRY.

MVC – Model, View, Controller

MVC separates business logic from presentation, so either can change without breaking the other.

Part

Responsibility

ABAP examples

Model

Data and business rules – reads/changes the database

Model class, CDS views, RAP business object

View

Shows the output to the user

ALV, Smart Form, classical list, Fiori UI

Controller

Receives user actions, calls the model, picks the view

Report/event handler class, Web Dynpro controller, OData service

The same model can feed an ALV, a form and a classical list. SAP frameworks built on MVC: Web Dynpro ABAP, BSP, and SAPUI5/Fiori with OData or RAP as the model.

Other patterns worth naming

Pattern

Idea

ABAP example

Observer

Objects subscribe to changes of another object

Events + SET HANDLER (Part 6)

Facade

One simple class in front of a complex subsystem

Wrapper class around several BAPIs

Strategy

Swap an algorithm behind an interface

Different pricing classes implementing one interface

Decorator

Add behaviour by wrapping an object with the same interface

Logging wrapper around a data-access class

Adapter

Make an incompatible interface fit

Class that maps an old FM to a new interface

Dependency injection

Pass dependencies in (constructor) instead of creating them inside

Inject a test double in ABAP Unit (Part 11)

Part 10 – SOLID and Clean ABAP

SOLID principles

Principle

Meaning

In ABAP

S – Single responsibility

A class has one reason to change

Separate data access, logic and output classes instead of one huge report class

O – Open/closed

Open for extension, closed for modification

New variant = new subclass or interface implementation, not another IF/CASE branch

L – Liskov substitution

A subclass must work wherever the superclass is expected

Redefinitions keep the contract (same meaning, no new mandatory preconditions)

I – Interface segregation

Many small interfaces beat one big one

zif_reader and zif_writer instead of one zif_everything

D – Dependency inversion

Depend on abstractions, not concrete classes

Type attributes as REF TO zif_… and inject them – the key to unit testing

Clean ABAP rules for classes, methods and exceptions

Clean ABAP is SAP's open style guide for ABAP (github.com/SAP/styleguides). Interviewers like to ask for its OO rules; the rule names below are the guide's own headings.

Area

Rule

Why

Classes

FINAL if not designed for inheritance

Inheritance is a contract; open it only on purpose

Classes

Members PRIVATE by default, PROTECTED only if needed

Small public surface, free to change

Classes

Prefer objects to static classes; prefer instance to static methods

Static calls can't be replaced by a test double

Classes

Prefer composition to inheritance (page 02)

Looser coupling than a deep class tree

Classes

Public instance methods should be part of an interface

Callers and tests depend on the interface (dependency inversion)

Classes

Prefer NEW to CREATE OBJECT

Shorter; CREATE OBJECT only for dynamic types

Classes

If your global class is CREATE PRIVATE, leave the CONSTRUCTOR public

Needed for correct compilation and syntax checks of global classes

Methods

Few IMPORTING parameters (at best less than three); split methods instead of adding OPTIONAL or Boolean parameters

One method, one job

Methods

Prefer RETURNING to EXPORTING; RETURN, EXPORT or CHANGE exactly one parameter – never a mix

Functional calls, readable call sites

Methods

Consider calling the RETURNING parameter result; avoid encodings and Hungarian prefixes

The guide prefers result = a + b to rv_result = iv_a + iv_b

Methods

Do one thing, keep methods small, fail fast

Easy to read and to test

Exceptions

Prefer exceptions to return codes; use class-based exceptions

Errors can't slip through

Exceptions

Use own super classes; throw one type of exception, sub-classes to distinguish cases

Callers catch one class per API

Exceptions

CX_STATIC_CHECK for manageable, CX_NO_CHECK for usually unrecoverable, consider CX_DYNAMIC_CHECK for avoidable errors

Matches the categories in Part 2

Exceptions

Dump for totally unrecoverable situations; prefer RAISE EXCEPTION NEW to RAISE EXCEPTION TYPE

RAISE SHORTDUMP, Part 3

Exceptions

Wrap foreign exceptions instead of letting them invade your code

Chaining with previous, Part 3

  • Prefixes (iv_, rv_, lo_ …) are still the convention in many projects and on this page. Know both views: follow your project's naming rules, and cite Clean ABAP when asked what SAP recommends.
  • RETURN expr (7.58): in a functional method, RETURN expr. assigns the value to the RETURNING parameter and leaves the method in one statement (details on page 01 Part 5).
METHOD net_price.
IF iv_gross <= 0.
RETURN 0.  "7.58: assign and leave
ENDIF.
RETURN iv_gross - iv_gross * mo_rates->discount_percent( iv_customer ) / 100.
ENDMETHOD.
  • Testing rules of the guide (given-when-then, one "when" per test, test seams only as a workaround) follow in Part 11.

Part 11 – ABAP Unit, injection and test doubles

ABAP Unit is the built-in unit test framework. Tests are local test classes in the test include of a global class (ADT tab "Test Classes", SE24 Goto → Local Definitions/Implementations → Local Test Classes) or in a program. They are transported with the class, but not generated or run in production systems (system setting, profile parameter abap/test_generation).

  • Test class: CLASS ltc_x DEFINITION FINAL FOR TESTING RISK LEVEL HARMLESS DURATION SHORT.
    • RISK LEVEL: HARMLESS (no persistent changes), DANGEROUS (changes data), CRITICAL (changes settings or customizing). The system setting decides which levels may run. Without the addition a test class counts as CRITICAL – the default – so always state the level.
    • DURATION: SHORT, MEDIUM, LONG – the time limits are set per system (transaction SAUNIT_CLIENT_SETUP).
  • Test methods: METHODS test_name FOR TESTING. – normal, concrete instance methods without parameters, private by convention. They are not abstract.
  • Fixture methods (fixed names, all optional): class_setup / class_teardown (static, once per class), setup / teardown (before / after each test method).
  • Structure each test as given – when – then: prepare the class under test and its doubles, make exactly one call of the code under test, then check the result with assertions.
  • Assertions in CL_ABAP_UNIT_ASSERT: assert_equals( act = … exp = … msg = … ), assert_true, assert_false, assert_initial, assert_not_initial, assert_bound, assert_differs, fail( ).
  • CLASS zcl_x DEFINITION LOCAL FRIENDS ltc_x. in the test include lets the test reach private components.
  • Run: Ctrl+Shift+F10 in ADT (or SE24/SE80 → Test → Unit Test), with coverage via Coverage As; ATC runs them too.
ABAP Unit lifecycle (class_setup, setup, test, teardown, class_teardown) and dependency injection with a test double
" ---- Production code: the dependency comes in through the constructor
INTERFACE zif_demo_rates PUBLIC.
METHODS discount_percent IMPORTING iv_customer       TYPE kunnr
RETURNING VALUE(rv_percent) TYPE i.
ENDINTERFACE.

CLASS zcl_demo_price_calc DEFINITION PUBLIC FINAL CREATE PUBLIC.
PUBLIC SECTION.
METHODS constructor IMPORTING io_rates TYPE REF TO zif_demo_rates.
METHODS net_price IMPORTING iv_customer   TYPE kunnr
iv_gross      TYPE i
RETURNING VALUE(rv_net) TYPE i.
PRIVATE SECTION.
DATA mo_rates TYPE REF TO zif_demo_rates.
ENDCLASS.

CLASS zcl_demo_price_calc IMPLEMENTATION.
METHOD constructor.
mo_rates = io_rates.
ENDMETHOD.
METHOD net_price.
rv_net = iv_gross - iv_gross * mo_rates->discount_percent( iv_customer ) / 100.
ENDMETHOD.
ENDCLASS.

" ---- Test include (local test classes of ZCL_DEMO_PRICE_CALC)
CLASS ltd_rates DEFINITION FOR TESTING.  "test double: no database
PUBLIC SECTION.
INTERFACES zif_demo_rates.
ENDCLASS.
CLASS ltd_rates IMPLEMENTATION.
METHOD zif_demo_rates~discount_percent.
rv_percent = 10.
ENDMETHOD.
ENDCLASS.

CLASS ltc_price_calc DEFINITION FINAL FOR TESTING RISK LEVEL HARMLESS DURATION SHORT.
PRIVATE SECTION.
DATA mo_cut TYPE REF TO zcl_demo_price_calc.  "class under test
METHODS setup.
METHODS discount_is_applied FOR TESTING.
METHODS zero_gross_gives_zero FOR TESTING.
ENDCLASS.

CLASS ltc_price_calc IMPLEMENTATION.
METHOD setup.
mo_cut = NEW #( io_rates = NEW ltd_rates( ) ).
ENDMETHOD.
METHOD discount_is_applied.
cl_abap_unit_assert=>assert_equals(
act = mo_cut->net_price( iv_customer = '0000001000' iv_gross = 200 )
exp = 180
msg = '10 % discount expected' ).
ENDMETHOD.
METHOD zero_gross_gives_zero.
cl_abap_unit_assert=>assert_equals(
act = mo_cut->net_price( iv_customer = '0000001000' iv_gross = 0 )
exp = 0 ).
ENDMETHOD.
ENDCLASS.

Test doubles – replace what you don't want to test

Which test double replaces which dependency: interface - own class or CL_ABAP_TESTDOUBLE; database tables - CL_OSQL_TEST_ENVIRONMENT; CDS view sources - CL_CDS_TEST_ENVIRONMENT; RAP BO - CL_BOTD_* environments; legacy code - TEST-SEAM

Technique

Replaces

Note

Own local class FOR TESTING

Any dependency behind an interface

Simplest; INTERFACES zif_x PARTIALLY IMPLEMENTED is allowed in test classes only

CL_ABAP_TESTDOUBLE

Global interfaces and global classes that are not FINAL

Framework creates and configures the double (configure_call, verify_expectations). Not for local classes or interfaces, FINAL, FOR TESTING or CREATE PRIVATE classes, or classes whose constructor has mandatory parameters

CL_OSQL_TEST_ENVIRONMENT

Database tables (and views) read in ABAP SQL

Redirects the SQL to test data you insert

CL_CDS_TEST_ENVIRONMENT

The sources of the CDS view under test

Tests CDS logic with your own data

CL_BOTD_TXBUFDBL_BO_TEST_ENV

A RAP BO your code uses via EML

Transactional buffer double: EML works on test instances you insert

CL_BOTD_MOCKEMLAPI_BO_TEST_ENV

A RAP BO your code uses via EML

Mocks EML calls: you configure the output for a given input and can verify the calls

TEST-SEAM / TEST-INJECTION

Code blocks in legacy code

Last resort when code can't be refactored

Injecting test doubles

A double is useless until the code under test uses it. Four ways to get it in – constructor injection is the default, the others fit special cases.

Technique

How

When

Constructor injection

Dependency is a constructor parameter (code above)

Default; the dependency is visible in the signature

Setter injection

The class creates the real dependency; a setter set_rates( ) replaces it

Optional or rarely changed dependencies

Parameter injection

The method that needs the dependency gets it as a parameter

Only one method needs it

Back-door injection

The test class is a LOCAL FRIEND and sets the private attribute directly

No public way to inject; keep the production API unchanged

" Setter injection
mo_cut = NEW #( ).
mo_cut->set_rates( NEW ltd_rates( ) ).

" Parameter injection
DATA(lv_net) = mo_cut->net_price( iv_customer = '0000001000'
iv_gross    = 200
io_rates    = NEW ltd_rates( ) ).

" Back-door injection: test include of the class under test
CLASS ltc_price_calc DEFINITION DEFERRED.
CLASS zcl_demo_price_calc DEFINITION LOCAL FRIENDS ltc_price_calc.
" … in ltc_price_calc:
METHOD setup.
mo_cut = NEW #( ).
mo_cut->mo_rates = NEW ltd_rates( ).  "private attribute, reachable through friendship
ENDMETHOD.
  • Injector / factory: production code gets its dependency from a factory class (zcl_demo_rates_factory=>get( )). A test-only injector class – a friend of the factory, FOR TESTING – stores a double in the factory, which then hands it out instead of the real object.
  • Clean ABAP: use LOCAL FRIENDS to reach a dependency-inverting constructor, but don't misuse it to invade the tested code; test the public methods, not the private internals.

CL_ABAP_TESTDOUBLE – let the framework build the double

METHOD discount_is_applied.
" given
DATA(lo_rates) = CAST zif_demo_rates( cl_abap_testdouble=>create( 'ZIF_DEMO_RATES' ) ).
cl_abap_testdouble=>configure_call( lo_rates
)->returning( 10 )->and_expect( )->is_called_once( ).
lo_rates->discount_percent( '0000001000' ).  "records which call returns 10
mo_cut = NEW #( io_rates = lo_rates ).
" when
DATA(lv_net) = mo_cut->net_price( iv_customer = '0000001000' iv_gross = 200 ).
" then
cl_abap_unit_assert=>assert_equals( act = lv_net exp = 180 ).
cl_abap_testdouble=>verify_expectations( lo_rates ).
ENDMETHOD.
  • configure_call( ) followed by one call of the double = "when called with these arguments, return this". and_expect( ) plus verify_expectations( ) also check how often it was called.
  • Limits: global interfaces and global, non-final classes only – not local classes or interfaces, and not classes that are FINAL, FOR TESTING, CREATE PRIVATE or have a constructor with mandatory parameters. Then write your own double class.

Replacing the database: CL_OSQL_TEST_ENVIRONMENT

CLASS ltc_flight_reader DEFINITION FINAL FOR TESTING RISK LEVEL HARMLESS DURATION SHORT.
PRIVATE SECTION.
CLASS-DATA go_sql_env TYPE REF TO if_osql_test_environment.
CLASS-METHODS class_setup.
CLASS-METHODS class_teardown.
METHODS setup.
METHODS price_is_read FOR TESTING RAISING cx_static_check.
ENDCLASS.

CLASS ltc_flight_reader IMPLEMENTATION.
METHOD class_setup.
go_sql_env = cl_osql_test_environment=>create(
i_dependency_list = VALUE #( ( 'SFLIGHT' ) ) ).  "SQL is redirected
ENDMETHOD.
METHOD setup.
DATA lt_flights TYPE STANDARD TABLE OF sflight WITH EMPTY KEY.
go_sql_env->clear_doubles( ).
lt_flights = VALUE #( ( carrid = 'LH' connid = '0400' fldate = '20260115' price = 500 ) ).
go_sql_env->insert_test_data( lt_flights ).
ENDMETHOD.
METHOD price_is_read.
DATA(lv_price) = NEW lcl_flight_reader( )->get_price( iv_carrid = 'LH'
iv_connid = '0400' ).
cl_abap_unit_assert=>assert_equals( act = lv_price exp = 500 ).
ENDMETHOD.
METHOD class_teardown.
go_sql_env->destroy( ).
ENDMETHOD.
ENDCLASS.
  • Create the environment once in class_setup, clear and fill it in setup, destroy it in class_teardown. The real table is never read or changed.
  • CL_CDS_TEST_ENVIRONMENT=>create( i_for_entity = 'ZI_DEMO_FLIGHT' ) works the same way for a CDS view under test: it doubles the view's sources so you can check its joins, filters and calculations.
  • SFLIGHT keeps the example close to the rest of the page; in ABAP Cloud you would use released or own tables (e.g. the /DMO/ flight model).

Test seams – a workaround for legacy code

" Production code
METHOD get_discount.
TEST-SEAM read_discount.
SELECT SINGLE discount FROM zdemo_discount
WHERE kunnr = @iv_customer
INTO @rv_percent.
END-TEST-SEAM.
ENDMETHOD.

" Test method in the test include
METHOD discount_from_seam.
TEST-INJECTION read_discount.
rv_percent = 10.
END-TEST-INJECTION.
cl_abap_unit_assert=>assert_equals( act = mo_cut->get_discount( '0000001000' ) exp = 10 ).
ENDMETHOD.
  • In a test run the injected code replaces the seam's block; in normal runs the original block runs. TEST-INJECTION is only allowed in test classes of the same program or class pool.
  • Clean ABAP: use test seams only as a temporary workaround – refactor towards an interface and injection. Availability in ABAP Cloud: check your release.

RAP business objects

  • Code that uses a RAP BO through EML is tested with the RAP BO test doubles (CL_BOTD_TXBUFDBL_BO_TEST_ENV transactional buffer double, CL_BOTD_MOCKEMLAPI_BO_TEST_ENV mock EML API); the BO's own handlers are tested with EML in the test class. Code: RAP › 12 · Extensibility & Testing.

Part 12 – OO in ABAP Cloud and S/4HANA

ABAP Cloud is SAP's development model for upgrade-stable, cloud-ready code: the only model in the SAP Business AI Platform, ABAP environment and S/4HANA Cloud Public Edition, and the recommended one (tier 1 of the clean core) in S/4HANA on-premise and Private Cloud. The OO language does not change – classes, interfaces, exceptions, events and ABAP Unit work exactly as on this page. What changes is which objects you may use, and how code is run and shown. Clean core background: Clean Core › 01 Clean Core.

Classic ABAP vs ABAP Cloud: SE24 to ADT, reports to IF_OO_ADT_CLASSRUN, CL_GUI_ALV_GRID and SALV to Fiori elements, Object Services to RAP, OTR to message classes, any SAP object to released APIs, dynamic access only to released objects

ABAP language versions

Language version

Where

What it allows

Standard ABAP

Classic on-premise code

The whole language, every repository object

ABAP for Cloud Development

SAP Business AI Platform, ABAP environment, S/4HANA Cloud, tier 1 software components on-premise

Restricted syntax (no SAP GUI, dynpro or list statements) and released APIs only

ABAP for Key Users

Key-user tools (custom fields and logic)

A further restricted subset

  • The version is a property of each object (ADT: Properties → General → ABAP Language Version), usually inherited from its software component. The syntax check enforces it – a forbidden statement is a syntax error, not a warning.
  • Classic code can be checked for cloud readiness with the ATC check variant ABAP_CLOUD_READINESS.

Released APIs: release contracts and API state

In ABAP Cloud you may only use SAP objects that SAP has released – classes, interfaces, CDS views, data elements, BAdIs. A release is a promise that the object stays stable across upgrades.

  • API state – ADT: open the object → Properties → API State. It shows whether the object is released, for which release contract, and – for deprecated objects – the successor. Released objects are also listed under Released Objects in the Project Explorer.
  • Release contracts: C1 – use system-internally, i.e. in your ABAP Cloud code: the contract that matters for classes and CDS views. C0 – stable extension points (extend an object). C2 – use as a remote API. Further contracts exist for special cases.
  • Your own classes are used freely inside their software component; to offer them to other components you release them yourself (API state, C1).
  • Dynamic access counts too: CREATE OBJECT … TYPE (name), dynamic method calls and dynamic ABAP SQL compile, but fail at runtime if the object is not released.
  • Finding replacements: the successor in the API state, SAP's Cloudification Repository (lists unreleased objects with their successors), released CDS views such as I_Product instead of tables, XCO instead of many function modules.

What is not available – and what replaces it

Classic technique

ABAP Cloud replacement

More on

SAP GUI: SE24, SE80, SE91, SE93

ADT in Eclipse (class and message class editors)

Page 01

Executable programs (REPORT), selection screens, WRITE lists

Class with IF_OO_ADT_CLASSRUN (run with F9, output with out->write( )); application jobs for batch

Page 01 Part 3

Dynpro, CL_GUI_* controls incl. CL_GUI_ALV_GRID, CL_SALV_TABLE, ALV with IDA

Fiori elements app on a RAP service

Page 04; RAP section

Object Services (persistence and transaction service)

RAP business object: CDS + behaviour pool + EML

Part 14; RAP

OTR texts in exception classes

Message classes (IF_T100_MESSAGE, IF_T100_DYN_MSG)

Part 4

Unreleased SAP classes, function modules, tables (e.g. SELECT FROM mara)

Released classes and CDS views (C1), XCO library

Below

OO transactions (SE93)

Fiori app (RAP/OData) or application job

Part 13

Shared objects, test seams

Check your release before relying on them

Parts 8, 11

RAP behaviour pool = ABAP Objects

The behaviour of a RAP business object is implemented in a behaviour pool: an ordinary global class with special additions. The real code is in local classes in its Local Types include (CCIMP) – a direct use of what pages 01–02 teach. Below is the skeleton of the Sales Order Approval app's pool; full anatomy and all method signatures: RAP › 04 · Behavior Definition & Behavior Pool.

" Global class = behaviour pool (normally empty)
CLASS zbp_r_salesorder DEFINITION PUBLIC ABSTRACT FINAL FOR BEHAVIOR OF zr_salesorder.
ENDCLASS.
CLASS zbp_r_salesorder IMPLEMENTATION.
ENDCLASS.

" Local Types: handler class for the entity SalesOrder
CLASS lhc_SalesOrder DEFINITION INHERITING FROM cl_abap_behavior_handler.
PRIVATE SECTION.
METHODS validateCustomer FOR VALIDATE ON SAVE
IMPORTING keys FOR SalesOrder~validateCustomer.
ENDCLASS.

CLASS lhc_SalesOrder IMPLEMENTATION.
METHOD validateCustomer.
" READ ENTITIES ... IN LOCAL MODE, then fill failed-salesorder / reported-salesorder
ENDMETHOD.
ENDCLASS.

" Local Types: saver class (managed BO with additional save)
CLASS lsc_ZR_SalesOrder DEFINITION INHERITING FROM cl_abap_behavior_saver.
PROTECTED SECTION.
METHODS save_modified REDEFINITION.
ENDCLASS.

CLASS lsc_ZR_SalesOrder IMPLEMENTATION.
METHOD save_modified.
" e.g. write the audit log or RAISE ENTITY EVENT
ENDMETHOD.
ENDCLASS.

Class

OO rules it uses

Behaviour pool ZBP_…

ABSTRACT FINAL – no instances, no subclasses; FOR BEHAVIOR OF links it to the behaviour definition

Handler lhc_<entity>

Local class INHERITING FROM CL_ABAP_BEHAVIOR_HANDLER; methods declared with FOR MODIFY, FOR READ, FOR VALIDATE, FOR DETERMINE, FOR … AUTHORIZATION, FOR … FEATURES; parameters (keys, result, failed, reported, mapped) are typed by RAP

Saver lsc_<bo>

Local class INHERITING FROM CL_ABAP_BEHAVIOR_SAVER; redefines the protected methods of the save sequence: finalize, check_before_save, adjust_numbers, save (or save_modified), cleanup, cleanup_finalize

  • You never create handler or saver objects: the RAP runtime instantiates and calls them – inversion of control, like an event handler.
  • Inside handlers: EML (READ ENTITIES … IN LOCAL MODE, MODIFY ENTITIES) instead of direct table access, errors via failed / reported (Part 4), and no COMMIT WORK or ROLLBACK WORK – the RAP transaction decides when to save.

XCO – released utility classes

The XCO library (Extension Components) is a set of released classes with a fluent OO API. In ABAP Cloud it replaces many function modules and system fields.

DATA(lv_user)  = xco_cp=>sy->user( )->name.                          "current user
DATA(lv_upper) = xco_cp=>string( `abap` )->to_upper_case( )->value.  "'ABAP'
DATA(lv_uuid)  = xco_cp=>uuid( )->value.                             "16-byte UUID
" today's date in the user's time zone, ISO format
DATA(lv_date)  = xco_cp=>sy->date( )->as( xco_cp_time=>format->iso_8601_extended )->value.
  • Further XCO areas: xco_cp_json (JSON), xco_cp_xlsx (Excel files, page 04), xco_cp_abap_repository (read repository objects such as classes) and more – see SAP Help "XCO library".
  • Other released helpers: CL_ABAP_CONTEXT_INFO (user, date, time zone), CL_SYSTEM_UUID, CL_ABAP_RANDOM_INT.

Part 13 – OO transactions (SE93)

A transaction code can start a method of a class directly instead of a report or dialog program.

  • SE93 → enter the new code → Create → short text → start object "Method of a class (OO transaction)".
  • Enter class and method. For a local class tick "Local in program" and enter the program name.
  • Leave "OO transaction model" unticked to call a normal method. Ticked, the transaction runs under the transaction service of Object Services (Part 14, legacy).
  • For an instance method the system creates the object first, so the constructor must not have mandatory parameters. Save and assign a package.
  • Modern alternative for users: a Fiori app (RAP/OData); for background logic: a report or application job that calls the class. ABAP Cloud has no SAP GUI transactions (Part 12).

Part 14 – Legacy: persistence service and transaction service

Legacy – know it for interviews. Object Services (persistence and transaction service) map objects to database tables without SQL. They still run in classic systems but are not available in ABAP Cloud and are not used in new S/4HANA development: RAP business objects replace them – CDS for the data model, EML (MODIFY ENTITIES, COMMIT ENTITIES) for changes. See RAP › 08 · EML.

Persistence service

  • Normally an object lives only while the program runs (the garbage collector frees it when no reference points to it, at the latest when the internal session ends). A persistent object keeps its state in the database; a transient object exists only in memory.
  • Persistence class ZCL_<name>: always global (SE24), always CREATE PROTECTED, implements IF_OS_STATE. Creating it generates two more classes:
    • Base agent ZCB_<name>: abstract, friend of the persistence class, holds the generated methods.
    • Agent (actor) ZCA_<name>: subclass of the base agent, CREATE PRIVATE, a singleton reached through its public static READ-ONLY attribute AGENT (filled by its static constructor on first access).
  • Mapping (Goto → Persistence Representation): map every table field; fields become attributes with generated GET_… methods (all) and SET_… methods (non-key fields).

Mapping type

Object identity

Key generated methods

Business key

The table's primary key

CREATE_PERSISTENT, GET_PERSISTENT, DELETE_PERSISTENT, CREATE_TRANSIENT, GET_TRANSIENT

Instance GUID

First field GUID with data element OS_GUID, generated by the system

CREATE_PERSISTENT, IF_OS_CA_PERSISTENCY~GET_PERSISTENT_BY_OID (returns OBJECT – down cast it), IF_OS_FACTORY~DELETE_PERSISTENT

Business key + GUID

Both: GUID as key, business key unique

Combination of the two

  • GUID mapping: every field except GUID becomes an attribute, and GET_… and SET_… methods are generated for all of them (the rule "SET_ only for non-key fields" is the business-key case).
  • Delete by GUID: IF_OS_FACTORY~DELETE_PERSISTENT expects an IF_OS_STATE reference. An interface cannot be instantiated, so read the object with GET_PERSISTENT_BY_OID( guid ), down cast it (?= / CAST) to the persistence class (which implements IF_OS_STATE) and pass that object.
" Business key mapping: table ZDEMO_EMP (EMPNO key, ENAME, DESIG)
DATA(lo_agent) = zca_demo_emp=>agent.  "the singleton agent
TRY.
DATA(lo_emp) = lo_agent->create_persistent( i_empno = 1001 ).  "CREATE
lo_emp->set_ename( 'DEMO USER' ).
COMMIT WORK.                       "now written to the DB

lo_emp = lo_agent->get_persistent( i_empno = 1001 ).  "READ
WRITE: / lo_emp->get_ename( ).
lo_emp->set_desig( 'DEVELOPER' ).                     "UPDATE
lo_agent->delete_persistent( i_empno = 1001 ).        "DELETE
COMMIT WORK.
CATCH cx_os_object_existing cx_os_object_not_found INTO DATA(lx_os).
MESSAGE lx_os TYPE 'I'.
ENDTRY.

Transaction service

Groups changes to persistent objects into one OO transaction that is committed or rolled back as a whole. Classes: CL_OS_SYSTEM, IF_OS_TRANSACTION_MANAGER, IF_OS_TRANSACTION.

DATA(lo_manager) = cl_os_system=>get_transaction_manager( ).
DATA(lo_tx)      = lo_manager->create_transaction( ).
lo_tx->start( ).
TRY.
zca_demo_emp=>agent->create_persistent( i_empno = 1002 ).
lo_tx->end( ).   "commit the whole transaction
CATCH cx_root.
lo_tx->undo( ).  "roll it back
ENDTRY.
  • In a normal report call CL_OS_SYSTEM=>INIT_AND_SET_MODES once first. In "OO transaction model" mode (SE93, Part 13) you must not code COMMIT WORK yourself – end( ) commits. Plain COMMIT WORK applies in compatibility mode.
  • Passing selection-screen values to the transaction method through ABAP memory (EXPORT … TO MEMORY) is also legacy; pass parameters to a method instead.

Part 15 – Interview questions

What are the three exception categories and how do you choose?

All inherit from CX_ROOT. CX_STATIC_CHECK: must be declared in RAISING, checked at compile time – for errors every caller must expect (most custom exceptions). CX_DYNAMIC_CHECK: checked at runtime – for errors the caller can avoid by checking first (CX_SY_ZERODIVIDE). CX_NO_CHECK: implicitly declared – for errors that can't sensibly be handled locally (resource shortage).

When does the CLEANUP block run? Can a TRY have CATCH and CLEANUP together?

Yes – any number of CATCH blocks plus one CLEANUP after them. CLEANUP runs only when an exception from this TRY is not caught here but by an outer handler; it must end normally through ENDTRY. If the exception is caught locally, or nobody catches it (short dump), CLEANUP does not run. ABAP has no FINALLY.

What does RAISING do, and what happens if an exception is not declared?

RAISING lets the exception propagate to the caller, who handles it. If a STATIC or DYNAMIC check exception leaves a method without being declared, the runtime raises CX_SY_NO_HANDLER with the original exception in PREVIOUS; unhandled, that dumps.

Classic exceptions vs class-based exceptions?

Classic: EXCEPTIONS in the signature, RAISE name or MESSAGE … RAISING, caller checks SY-SUBRC; no object, no text, no propagation through several levels. Class-based: exception objects with texts and PREVIOUS chaining, propagate automatically, handled with TRY/CATCH. One method can't mix both; new code uses class-based exceptions.

How do you create a custom exception class with a message from a message class?

Create ZCX_… in SE24/ADT inheriting from CX_STATIC_CHECK (usually), tick "With message class" so it implements IF_T100_MESSAGE (or IF_T100_DYN_MSG), define exception ID constants (MSGID, MSGNO, ATTR1–4) and attributes for the placeholders. Raise with RAISE EXCEPTION TYPE zcx_… EXPORTING textid = … or, with IF_T100_DYN_MSG, RAISE EXCEPTION TYPE zcx_… MESSAGE e001(zmsg) WITH …. OTR texts are legacy.

What is the difference between RESUME and RETRY?

RESUME continues in the raising method right after a RAISE RESUMABLE EXCEPTION; it needs CATCH BEFORE UNWIND and RESUMABLE in every RAISING clause on the way. RETRY restarts the whole TRY block from the beginning – fix the cause first or you loop forever.

Explain events in ABAP – what are the steps?

Declare the event with EVENTS/CLASS-EVENTS (EXPORTING parameters by value), declare a handler method FOR EVENT … OF class, register it with SET HANDLER before the event is raised, raise it with RAISE EVENT inside a method. Handlers are never called directly; unregistered handlers don't run. It is the observer pattern; ALV events (double_click, hotspot_click) work the same way.

Instance event vs static event – and what is SENDER?

Instance events (EVENTS) are raised only in instance methods and registered per sender (FOR lo_obj or FOR ALL INSTANCES). Static events (CLASS-EVENTS) can be raised in any method of the class and are registered without FOR. SENDER is the implicit parameter of instance events – a reference to the object that raised it. ACTIVATION abap_false deregisters a handler.

What is RTTS? How do you create an internal table for a table name known only at runtime?

RTTS = RTTI (describe types: CL_ABAP_TYPEDESCR=>describe_by_name/data/object_ref) + RTTC (create types: CL_ABAP_STRUCTDESCR=>get, CL_ABAP_TABLEDESCR=>create). Get the structure description, build the table type, CREATE DATA lr TYPE HANDLE lo_type, ASSIGN lr->* to a field symbol, SELECT FROM (name). Shortcut: CREATE DATA lr TYPE STANDARD TABLE OF (name). Always validate the name (allow-list, CL_ABAP_DYN_PRG) and check authorization – otherwise users can read any table.

How do you implement a singleton? Give a factory example from SAP.

Class FINAL CREATE PRIVATE, a private static attribute holding the instance, and a public static get_instance method that creates it on first call and always returns the same reference. Factory example: CL_SALV_TABLE=>FACTORY creates the ALV object for you; your own factories return an interface reference and choose the implementing class inside.

How do you write an ABAP Unit test, and how do you isolate dependencies?

Local class FOR TESTING with RISK LEVEL and DURATION, test methods FOR TESTING (concrete, no parameters), fixtures setup/teardown and class_setup/class_teardown, checks with CL_ABAP_UNIT_ASSERT. Isolate dependencies by injecting interfaces (constructor injection) and passing a test double – own class, CL_ABAP_TESTDOUBLE, CL_OSQL_TEST_ENVIRONMENT for tables, CL_CDS_TEST_ENVIRONMENT for CDS. Run with Ctrl+Shift+F10.

What is the persistence service, and what replaces it in S/4HANA?

Object Services map a persistence class (CREATE PROTECTED, IF_OS_STATE) to a table by business key, GUID or both; the generated singleton agent class (ZCA_…=>AGENT) offers CREATE/GET/DELETE_PERSISTENT, and the transaction service (CL_OS_SYSTEM) bundles changes. It is legacy and not available in ABAP Cloud; new development uses RAP business objects with CDS and EML.

What changes for object-oriented development in ABAP Cloud?

The OO language stays the same; the rules around it change. Objects use the language version ABAP for Cloud Development, so only released SAP APIs can be used (also dynamically) and SAP GUI techniques are gone: no SE24 (ADT instead), no reports or WRITE lists (IF_OO_ADT_CLASSRUN, application jobs), no CL_GUI_ALV_GRID or SALV (Fiori elements on RAP), no Object Services (RAP BOs), no OTR texts (message classes). XCO and released CDS views replace many function modules and tables.

What is a released API and what does the C1 contract mean?

A released API is an SAP object that SAP promises to keep stable across upgrades. ADT shows it on the API State tab: released or not, for which release contract, and the successor if it is deprecated. C1 means "use system-internally" – the object may be used in ABAP Cloud code; C0 covers extension points and C2 remote APIs. Classic code is checked with the ATC variant ABAP_CLOUD_READINESS.

What is a RAP behaviour pool, and which OO concepts does it use?

A global class ABSTRACT FINAL … FOR BEHAVIOR OF the BO, normally empty. The logic sits in local classes: handler classes inheriting from CL_ABAP_BEHAVIOR_HANDLER with methods FOR MODIFY / READ / VALIDATE / DETERMINE, and a saver class inheriting from CL_ABAP_BEHAVIOR_SAVER that redefines the save-sequence methods. The RAP runtime creates and calls them; errors go into failed and reported, not into exceptions, and handlers never COMMIT.

How do you get a test double into the code under test, and when is CL_ABAP_TESTDOUBLE not enough?

Constructor injection by default; setter or parameter injection for optional or single-use dependencies; back-door injection through LOCAL FRIENDS; or a factory with a test injector. Databases are replaced with CL_OSQL_TEST_ENVIRONMENT, CDS sources with CL_CDS_TEST_ENVIRONMENT, RAP BOs with the CL_BOTD_* environments, legacy blocks with test seams. CL_ABAP_TESTDOUBLE only doubles global interfaces and global classes that are not FINAL, FOR TESTING or CREATE PRIVATE and have no mandatory constructor parameters. And: without RISK LEVEL a test class counts as CRITICAL.

Exception, ASSERT or RAISE SHORTDUMP – which one when?

An exception (RAISE EXCEPTION NEW) for errors that can happen and that a caller may handle; chain the cause with previous. ASSERT for conditions that can only be false through a bug (ASSERTION_FAILED). RAISE SHORTDUMP (7.53) for unrecoverable states: it cannot be caught and writes the exception class and its text into the short dump. Clean ABAP: dump only for totally unrecoverable situations.

🏠 Start Here · ◀ 02 · Inheritance & Interfaces · 04 · ALV Reporting ▶ · Sections: CORE ABAP | OOPS ABAP | ABAP on HANA | Clean Core | RAP | ABAP Points | SAP Fiori | SAPUI5 | Mobile Development (MDK) | BTP Foundations | BTP Development | CAP | SAP Build | ABAP on BTP | Integration Suite | SAP Business AI | SAP BASIS | Security | SAP SDLC

Functional: FICO ABAP | TRM ABAP | VIM | SAP BIS | SD ABAP | MM ABAP | PP ABAP | QM ABAP | PM ABAP | PS ABAP | EWM | TM ABAP | GTM ABAP | EHS ABAP | HR ABAP | BW | SAP Datasphere | SAP Business Data Cloud | SAP MDG | SAP Analytics Cloud | SAP Ariba | SAP CX | SAP IBP