ERPClimb logoERPClimb
Behavior Implementations
RAP / CDS / ODataintermediate 12 min read

Behavior Implementations Part 1: The Behavior Pool — Handler and Saver Classes

Free sample lesson · open to everyone

Key takeaway

Understand the anatomy of a behavior pool: the global ZBP class, local handler and saver classes, how methods are generated from the BDEF, implicit parameters, derived types and the %-components you use in every method.

In this lessonShow sections

The situation: a real project scenario

A team's first RAP BO grew into one 1,800-line handler class for all entities, with helper methods mixed in and several methods working on the first key only. Bugs appeared whenever Fiori sent more than one instance, for example in mass actions.

In a refactoring, they split the code into one handler per entity, moved reusable logic into a separate domain class, and applied the golden rules (process all rows, EML in local mode, %tky, failed/reported). The class became readable, the multi-instance bugs disappeared, and new team members could find the method for a BDEF element immediately.

Explanation

This series explains the mechanics of the behavior pool across five parts: this lesson covers the handler and saver classes, Part 2 covers determinations and validations without side effects, Part 3 covers actions, results and user-facing messages, Part 4 covers the save sequence, late numbering and unmanaged save in the saver, and Part 5 covers performance, unit testing and debugging.

The behavior definition says what a BO can do; the behavior implementation is the ABAP code that does the non-standard parts, and the Managed RAP series shows these mechanics applied in a full build.

The behavior pool is a global class, for example ZBP_R_PURCHREQ, declared "ABSTRACT FINAL FOR BEHAVIOR OF zr_purchreq" — but the global class itself stays empty. All of the actual code lives in the local types include, under the Local Types tab in ADT, inside local classes.

Handler classes inherit from cl_abap_behavior_handler, usually one per entity (lhc_PurchaseRequest, lhc_Item), and contain the interaction-phase methods: determinations, validations, actions, functions, authorization, feature control, prechecks, and — for unmanaged BOs — also CRUD, read and lock. The saver class inherits from cl_abap_behavior_saver (lsc_…) and is only needed for save-phase code: finalize, check_before_save, adjust_numbers, save or save_modified, cleanup, and cleanup_finalize.

None of these classes are created by hand — placing the cursor on the class name or a BDEF element and using the ADT quick fix (Ctrl+1) generates them.

Each BDEF element produces a method with its own special FOR clause.

A determination becomes "METHODS setInitialStatus FOR DETERMINE ON MODIFY IMPORTING keys FOR PurchaseRequest~setInitialStatus." A validation becomes "METHODS validateDescription FOR VALIDATE ON SAVE IMPORTING keys FOR PurchaseRequest~validateDescription." An action becomes "METHODS approve FOR MODIFY IMPORTING keys FOR ACTION PurchaseRequest~approve RESULT result." Instance feature control becomes "METHODS get_instance_features FOR INSTANCE FEATURES IMPORTING keys REQUEST requested_features FOR PurchaseRequest RESULT result." And global authorization becomes "METHODS get_global_authorizations FOR GLOBAL AUTHORIZATION IMPORTING REQUEST requested_authorizations FOR PurchaseRequest RESULT result." None of these methods are ever called directly — RAP calls them at the right time on its own.

Beyond the parameters that are explicitly declared, most methods also carry implicit changing parameters: failed, for instances that failed, carrying %fail-cause; reported, for messages per instance (%msg) or unbound ones (%other); and mapped, for the key mapping of new instances (%cid to key), present in methods that create. Their types are derived from the BO, so they get addressed per entity, as in failed-purchaserequest or reported-item.

RAP also generates derived types for everything — "TYPE TABLE FOR CREATE zr_purchreq", "TYPE TABLE FOR READ RESULT zr_purchreq", "TYPE RESPONSE FOR FAILED zr_purchreq" — and these are rarely declared explicitly, since inline declarations (DATA(...)) and VALUE #( ) can infer them.

A handful of %-components come up constantly and are worth knowing well. %tky is the transactional key — the key plus %is_draft when draft is involved — and should be used everywhere to identify instances. %key holds only the key fields. %cid and %cid_ref are the content ID of a new instance and a reference to it within one request. %pid is the preliminary ID used with late numbering. %is_draft marks a draft versus an active instance. %control shows which fields were actually supplied, field by field. %param carries an action's parameter or its result data. %msg is the message object, %element names the field or fields to highlight, %state_area names the message group, and %fail-cause gives the reason inside failed. %other holds messages that aren't bound to any instance.

A few golden rules apply to all handler code: every method receives a table, so all rows must be processed, not just the first; reading happens with READ ENTITIES … IN LOCAL MODE and changing with MODIFY ENTITIES … IN LOCAL MODE; %tky should be used rather than raw key fields; there must be no COMMIT, no direct DML on the BO's own tables, and no dialogs; and problems must be reported via failed and reported, never by raising unhandled exceptions or using MESSAGE statements.

After Part 1, the overall map of a behavior pool should be clear; Part 2 moves on to implementing determinations and validations correctly.

Expert RAP implementation lab

BEHAVIOR IMPLEMENTATIONS · PART 1ERPClimb.com

Inside a RAP behavior pool

Architecture · BDEF contract and local implementations

Global behavior pool

ZBP_I_Travel

FOR BEHAVIOR OF · BDEF owns the contract

Handler: business operations

Methods for actions, determinations, validations, instance authorization and other declared behavior operate under the RAP runtime's handler contracts.

CLASS lhc_Travel DEFINITION INHERITING FROM
  cl_abap_behavior_handler.
  PRIVATE SECTION.
    METHODS approve FOR MODIFY
      IMPORTING keys FOR ACTION Travel~approve
      RESULT result.
ENDCLASS.
Don't mix the two phases

A behavior pool is the implementation container, not a database table. Generated method signatures and available hooks depend on the BDEF and selected implementation type.

Conceptual ABAP RAP teaching examples, not live SAP execution traces. Check behavior syntax and enabled hooks against your ABAP platform release.

Code example

ABAP Code
" ===== Global class (generated, stays empty) =====CLASS zbp_r_purchreq DEFINITION PUBLIC ABSTRACT FINAL FOR BEHAVIOR OF zr_purchreq.ENDCLASS.CLASS zbp_r_purchreq IMPLEMENTATION.ENDCLASS. " ===== Local Types include: handler for the root entity =====CLASS lhc_PurchaseRequest DEFINITION INHERITING FROM cl_abap_behavior_handler.   " inheriting from this base class is what registers it as a RAP handler  PRIVATE SECTION.    METHODS get_global_authorizations FOR GLOBAL AUTHORIZATION       " instance-independent check, e.g. is create allowed at all      IMPORTING REQUEST requested_authorizations FOR PurchaseRequest RESULT result.     METHODS get_instance_authorizations FOR INSTANCE AUTHORIZATION   " per-instance check, e.g. may THIS user update/delete THIS request      IMPORTING keys REQUEST requested_authorizations FOR PurchaseRequest RESULT result.     METHODS get_instance_features FOR INSTANCE FEATURES              " drives the field(features)/action(features) switches declared in the BDEF      IMPORTING keys REQUEST requested_features FOR PurchaseRequest RESULT result.     METHODS setInitialStatus FOR DETERMINE ON MODIFY      IMPORTING keys FOR PurchaseRequest~setInitialStatus.     METHODS validateDescription FOR VALIDATE ON SAVE      IMPORTING keys FOR PurchaseRequest~validateDescription.     METHODS approve FOR MODIFY      IMPORTING keys FOR ACTION PurchaseRequest~approve RESULT result.ENDCLASS. " ===== Handler for the child entity =====CLASS lhc_Item DEFINITION INHERITING FROM cl_abap_behavior_handler.  PRIVATE SECTION.    METHODS calculateTotal FOR DETERMINE ON MODIFY      IMPORTING keys FOR Item~calculateTotal.ENDCLASS. " ===== Saver (only if save-phase code is needed) =====CLASS lsc_zr_purchreq DEFINITION INHERITING FROM cl_abap_behavior_saver.  PROTECTED SECTION.    METHODS adjust_numbers REDEFINITION.     " late numbering    METHODS save_modified  REDEFINITION.     " additional/unmanaged saveENDCLASS. " ===== Using implicit parameters and %-components =====METHOD validateDescription.  READ ENTITIES OF zr_purchreq IN LOCAL MODE    ENTITY PurchaseRequest FIELDS ( Description ) WITH CORRESPONDING #( keys )    RESULT DATA(requests).                        " derived type inferred   LOOP AT requests INTO DATA(request) WHERE Description IS INITIAL.    APPEND VALUE #( %tky = request-%tky ) TO failed-purchaserequest.      " implicit    APPEND VALUE #( %tky = request-%tky                    %msg = new_message_with_text(                             severity = if_abap_behv_message=>severity-error                             text     = 'Description is required' )                    %element-Description = if_abap_behv=>mk-on )      TO reported-purchaserequest.                                        " implicit  ENDLOOP.ENDMETHOD. " Explicit derived types, when you need them:" DATA create_tab TYPE TABLE FOR CREATE zr_purchreq." DATA read_res   TYPE TABLE FOR READ RESULT zr_purchreq." DATA failed_all TYPE RESPONSE FOR FAILED zr_purchreq.

Watch out

Common mistakes

  • Putting code into the global class instead of the local types include.
  • One giant handler for all entities.
  • Processing only keys[ 1 ].
  • Using key fields instead of %tky, breaking draft.
  • Raising MESSAGE or unhandled exceptions instead of filling failed and reported.
  • Writing methods by hand instead of generating them from the BDEF.

Do this

Best practices

  • Generate method stubs with the ADT quick fix.
  • One handler class per entity; saver only when needed.
  • Extract larger reusable logic into separate classes called from handlers.
  • Learn the %-components; use %tky everywhere.
  • Follow the golden rules in every method and check them in code reviews.

In the interview

Interview angle

Questions: "What is a behavior pool?", "What is the difference between a handler and a saver class?", "What are failed, reported and mapped?", "What is %tky?"
Strong answer: the behavior pool is a global class FOR BEHAVIOR OF the BO with local handler classes (interaction phase: determinations, validations, actions, authorization, feature control, and CRUD in unmanaged) and an optional saver class (save sequence). Methods are generated from BDEF elements. failed, reported and mapped are implicit response parameters. %tky is the key plus %is_draft, used to identify instances in draft-enabled BOs.

Practice this lesson

Quick check

0 of 3 questions attempted

Question 1 of 3

Which statement about the structure of a behavior pool is correct?

Practise this in an interview

Answer in your own words and get instant feedback, the way an interviewer would judge it.

1What is a behavior pool, and what is the difference between its handler and saver classes?

2Explain %tky, %key, %cid, %pid, %control and %param. Which mistake happens when developers use key fields instead of %tky?

Try a related Code Lab

This published exercise covers the same SAP topic. Apply the ideas in a hands-on scenario, then return to review your answers.

Open: SELECT Inside LOOP in a RAP Validation →

See it in code

Each example starts from a requirement, shows the design, then the code step by step with a plain-language explanation of every part.

Was this lesson helpful?

Keep exploring

Check before use: lesson examples are educational, not a guarantee of correctness for your SAP edition or release. Sample code has not been executed on your SAP system. Confirm API availability, syntax, authorizations and business impact in an approved development or test environment.