Let a service delegate a job

A delivery service needs a fee, but fee rules may change by region or promotion. Rather than subclassing the whole service for each fee variation, give it a collaborator that knows how to calculate a fee. This is composition: one object contains or uses another object.

Depend on a capability

INTERFACE lif_fee_policy.
  METHODS amount RETURNING VALUE(result) TYPE i.
ENDINTERFACE.

The service stores a reference to the contract, not one specific implementation:

CLASS lcl_delivery_service DEFINITION.
  PUBLIC SECTION.
    METHODS constructor IMPORTING io_policy TYPE REF TO lif_fee_policy.
    METHODS fee RETURNING VALUE(result) TYPE i.
  PRIVATE SECTION.
    DATA policy TYPE REF TO lif_fee_policy.
ENDCLASS.

METHOD constructor.
  policy = io_policy.
ENDMETHOD.

METHOD fee.
  result = policy->amount( ).
ENDMETHOD.

Providing the dependency through the constructor makes the relationship visible and allows tests to pass a fake policy. Production code should also decide how to handle an unbound/invalid dependency.

Composition or inheritance?

Use inheritance for a true subtype that can substitute for its parent. Use composition when one object delegates a capability to another, especially when that capability may vary independently. Composition keeps class hierarchies shallower and generally improves test substitution.

Practice

Create the interface and collaborator, inject it into the delivery service, delegate its calculation, and set result. Add mode-specific output. The browser only checks for expected fragments.

Version note: Object references and interfaces are ABAP Objects features. Concrete dependencies must also comply with the target language version and released API rules.

Sources

Developer practice · ABAP

Practice: delegate a fee calculation

Create a fee-policy interface and a service that uses it. Delegate the calculation and assign the result.

Choose your ABAP environment

This choice changes the output pattern checked here: WRITE belongs in a classic executable report, while out->write( ) uses the supplied output reference in an ABAP Cloud class-run method. It does not switch the language version of the other code; check release and API availability in your target system.

Complete the task and include the output statement shown for your selected environment. Variable names can differ if you use them consistently. This browser checker checks structure only; it does not compile or run ABAP.

0 required structures detected · 0 checks