Interfaces and Factory Methods in Practical ABAP
Learn how interfaces and factory methods make ABAP code flexible and testable.
Explanation
An interface defines what a class can do without saying how it does it. Multiple classes can implement the same interface differently. A factory method centralizes object creation logic and returns the correct implementation based on input such as company code, country, document type or process type. This is powerful in SAP projects where business rules vary by region or process. Instead of writing long IF blocks everywhere, one factory decides which implementation to use. This improves flexibility, testing and maintainability.
Code example
INTERFACE lif_validator. METHODS validate IMPORTING iv_value TYPE string RETURNING VALUE(rv_valid) TYPE abap_bool.ENDINTERFACE. CLASS lcl_customer_validator DEFINITION. PUBLIC SECTION. INTERFACES lif_validator.ENDCLASS. CLASS lcl_customer_validator IMPLEMENTATION. METHOD lif_validator~validate. rv_valid = xsdbool( iv_value IS NOT INITIAL ). ENDMETHOD.ENDCLASS. CLASS lcl_validator_factory DEFINITION. PUBLIC SECTION. CLASS-METHODS get_validator RETURNING VALUE(ro_validator) TYPE REF TO lif_validator.ENDCLASS. CLASS lcl_validator_factory IMPLEMENTATION. METHOD get_validator. ro_validator = NEW lcl_customer_validator( ). ENDMETHOD.ENDCLASS.Real project scenario
A tax calculation process differs by country. Instead of writing country-specific IF logic in every report, create one tax calculator interface, multiple country implementations and a factory that returns the correct calculator.
Common mistakes
- Creating interfaces without real need. - Putting implementation logic inside factory. - Using factory but still hardcoding logic everywhere. - Not programming against the interface type.
Best practices
- Use interfaces when multiple implementations are possible. - Keep factory responsible only for object creation decision. - Program to interface, not concrete class. - Keep implementations focused.
Interview angle
Architect-level interviews often ask how to remove long IF/CASE blocks. Interface plus factory is a strong answer.