Case Statement usage
Case statements in ABAP are great. Not only do they let you handle your logic flow like other control flow statements but also provide a clean/ better readable way to branch into multiple sublogics.
A typical use of a case statement is something like this as [CASE variable: WHEN value]:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CASE lv_traffic_light. | |
WHEN 'GREEN'. | |
lv_message = 'Go Ahead'. | |
WHEN 'YELLOW'. | |
lv_message = 'Be Cautious'. | |
WHEN 'RED'. | |
lv_message = 'STOP!'. | |
ENDCASE. |
However, they can also be used as [CASE values: WHEN variable] way.
Let's assume:
We have to validate and report if some variables have data or not.
One way to do it would be:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
IF p_1 IS INITIAL. | |
MESSAGE 'no data in P1' TYPE 'E' . | |
ENDIF. | |
IF p_2 IS INITIAL. | |
MESSAGE 'no data in P2' TYPE 'E' . | |
ENDIF. | |
IF p_3 IS INITIAL. | |
MESSAGE 'no data in P3' TYPE 'E' . | |
ENDIF. |
Another way to use Case statement:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CASE SPACE. | |
WHEN P_1. | |
MESSAGE 'no data in P1' TYPE 'E' . | |
WHEN P_2. | |
MESSAGE 'no data in P2' TYPE 'E' . | |
WHEN P_3. | |
MESSAGE 'no data in P3' TYPE 'E' . | |
ENDCASE. | |
I prefer this way as it increases readability and in my opinion cleaner.