Recently I will deliver a session regarding dependency inversion principle to my team.
- ABAP Dependency Injection – An implementation approach
- Shoot Me Up ABAP
- Dependency Injection for ABAP
- MockA in github
Thanks a lot for efforts spent by authors of them!
Let me begin with a simple example. In real world I have a switch. By pressing it, the lamp connected by that switch is turned on. With switch pressed for second time, the lamp is turned off. That’s all.
Implementation without using Dependency injection
And a ZCL_LAMP which simply implements this interface:
CLASS ZCL_LAMP IMPLEMENTATION. method ZIF_SWITCHABLE~OFF. WRITE: / 'lamp off'. endmethod. method ZIF_SWITCHABLE~ON. WRITE: / 'lamp on'. endmethod. ENDCLASS.
The switch has a push method to toggle:
METHOD push. IF isswitchon = abap_true. mo_switchable->off( ). isswitchon = abap_false. ELSE. mo_switchable->on( ). isswitchon = abap_true. ENDIF. ENDMETHOD.
And a setter method is needed to inject the switchable instance:
method SET_SWITCHABLE. mo_switchable = io_switchable. endmethod.
Consumer code – version one without using dependency injection
- line 8: create lamp instance
- line 9: create switch instance
- line 11: connect switch with lamp
Implementation using ABAP Summer
When the same requirement is implemented in Java Spring, the logic in line 11 could completely be avoided, with help of various powerful annotation like @Autowired, @Named, @Inject etc. Thanks to Java Spring container, lots of labor work has been done by it under the hood, saving lots of routine effort from application developers so that they can only concentrate on the core business logic. For example, in Java using Spring, all developers need to do is to add annotation @Inject on top of attribute switchable – in the runtime Spring will guarantee that the annotated implementation for this interface is instantiated automatically.
How can we simulate the similar logic of Spring now in ABAP Summer?
2. And below is my consumer code, no more manual instance initialization and manual setter call. Very clean, isn’t it?
data(summer) = zcl_summer=>get_instance( ). data(lo_switch) = cast zcl_switch( summer->get_bean( EXPORTING iv_bean_name = 'ZCL_SWITCH' ) ). lo_switch->push( ). lo_switch->push( ).
How does ABAP summer work?
More thought on ABAP annotation
- Fibonacci Sequence in ES5, ES6 and ABAP
- Java byte code and ABAP Load
- How to write a correct program rejected by compiler: Exception handling in Java and in ABAP
- An small example to learn Garbage collection in Java and in ABAP
- String Template in ABAP, ES6, Angular and React
- Try to access static private attribute via ABAP RTTI and Java Reflection