OOP ABAP
ABAP DevelopmentAdvanced

Composition vs Inheritance in ABAP Design

Understand why composition is often safer than inheritance in real ABAP projects.

Explanation

Inheritance allows one class to extend another class. It is useful when there is a true is-a relationship. For example, a specific validator can inherit from a generic validator if the design is stable. But inheritance can make code tightly coupled and harder to change. Composition means one class uses another class as a dependency. It is often safer because behavior can be changed by replacing the composed object. In real SAP projects, composition is usually preferred for business services because requirements change frequently. Inheritance should be used carefully and only when the relationship is natural and stable.

Code example

ABAP Code
INTERFACE lif_tax_calculator.  METHODS calculate_tax    IMPORTING iv_amount TYPE netwr    RETURNING VALUE(rv_tax) TYPE netwr.ENDINTERFACE. CLASS lcl_invoice_service DEFINITION.  PUBLIC SECTION.    METHODS constructor IMPORTING io_tax TYPE REF TO lif_tax_calculator.    METHODS calculate_total IMPORTING iv_amount TYPE netwr RETURNING VALUE(rv_total) TYPE netwr.  PRIVATE SECTION.    DATA mo_tax TYPE REF TO lif_tax_calculator.ENDCLASS.

Real project scenario

A billing engine initially uses inheritance for every provider variant. Later, replacing it with interface-based composition and factory creation reduces subclasses and makes testing easier.

Common mistakes

- Using inheritance only for code reuse. - Creating deep inheritance chains. - Putting business variant logic in subclasses too early. - Not considering interfaces and composition.

Best practices

- Use inheritance only for true is-a relationships. - Prefer composition for changing business behavior. - Use interfaces to decouple caller and implementation. - Avoid deep inheritance hierarchies.

Interview angle

Senior candidates should explain that inheritance is useful but overuse creates tight coupling. Composition plus interfaces is often more flexible.