COND and SWITCH
Replacement of IF-ELSEIF ladder and CASE statements
So lets see how we can actually take use these operators , please note that with these we can't debug each and every iterations which is possible with IF-ELSEIF and CASE.
3.10.1 COND
OLD :
*If-else-if ladder in ECC
data : lv_1 type i VALUE '9',
lv_2 type i VALUE '9',
lv_result type string.
IF 1 = 2.
lv_result = 'Wrong'.
ELSEIF ( 2 GT 4 OR 3 NE 3 ).
lv_result = 'Both condition failed'.
ELSEIF ( ( 5 BETWEEN 5 and 8 ) AND 7 LE 6 ).
lv_result = 'Any one condition failed'.
ELSEIF lv_1 LE lv_2.
lv_1 = lv_2 + 1.
lv_result = 'Finally you are right '.
ELSE.
lv_result = 'All condition failed'.
ENDIF.
WRITE : / lv_result, 'lv_1 =' ,lv_1, 'lv_2 =' ,lv_2,'(If-else-if ladder)'.
Output :
NEW :
We can replace if else ladder with below COND expression if the resultant variable is same
Example in new Abap:
DATA(lv_result_cond) = COND string(
WHEN 1 EQ 2 THEN 'wrong'
WHEN 2 GT 4 OR 3 NE 3 THEN 'wrong'
WHEN 5 EQ 5 AND 7 LE 6 THEN 'wrong'
WHEN lv_1 LE lv_2 THEN 'correct'
ELSE 'All failed'
).
WRITE : / lv_result_cond,'lv_1 =' ,lv_1, 'lv_2 =' ,lv_2, '( using COND operator in new ABAP )'.
Output :
OLD :
*If-else-if ladder in ECC
data : lv_1 type i VALUE '9',
lv_2 type i VALUE '9',
lv_result type string.
IF 1 = 2.
lv_result = 'Wrong'.
ELSEIF ( 2 GT 4 OR 3 NE 3 ).
lv_result = 'Both condition failed'.
ELSEIF ( ( 5 BETWEEN 5 and 8 ) AND 7 LE 6 ).
lv_result = 'Any one condition failed'.
ELSEIF lv_1 LE lv_2.
lv_1 = lv_2 + 1.
lv_result = 'Finally you are right '.
ELSE.
lv_result = 'All condition failed'.
ENDIF.
WRITE : / lv_result, 'lv_1 =' ,lv_1, 'lv_2 =' ,lv_2,'(If-else-if ladder)'.
Output :
NEW :
We can replace if else ladder with below COND expression if the resultant variable is same
Example in new Abap:
DATA(lv_result_cond) = COND string(
WHEN 1 EQ 2 THEN 'wrong'
WHEN 2 GT 4 OR 3 NE 3 THEN 'wrong'
WHEN 5 EQ 5 AND 7 LE 6 THEN 'wrong'
WHEN lv_1 LE lv_2 THEN 'correct'
ELSE 'All failed'
).
WRITE : / lv_result_cond,'lv_1 =' ,lv_1, 'lv_2 =' ,lv_2, '( using COND operator in new ABAP )'.
Output :
3.10.2. SWITCH
OLD :
Case Condition :
DATA : lv_indicator like scal-indicator,
lv_day(10) type c.
CALL FUNCTION 'DATE_COMPUTE_DAY'
EXPORTING
date = sy-datum
IMPORTING
day = lv_indicator.
CASE lv_indicator.
WHEN 1.
lv_day = 'Monday'.
WHEN 2.
lv_day = 'Tuesday'.
WHEN 3.
lv_day = 'Wednesday'.
WHEN 4.
lv_day = 'Thursday'.
WHEN 5.
lv_day = 'Friday'.
WHEN 6.
lv_day = 'Saturday'.
WHEN 7.
lv_day = 'Sunday'.
WHEN OTHERS.
lv_day = 'Invalid'.
ENDCASE.
WRITE : /'Today''s date is ',lv_day.
Output :
NEW :
Replace case with switch in new abap , operand occurs only once.
DATA(Lv_DAY_switch) = SWITCH char10( lv_indicator
WHEN 1 THEN 'Monday'
WHEN 2 THEN 'Tuesday'
WHEN 3 THEN 'Wednesday'
WHEN 4 THEN 'Thursday'
WHEN 5 THEN 'Friday'
WHEN 6 THEN 'Saturday'
WHEN 7 THEN 'Sunday'
ELSE 'Invalid' ).
WRITE : /'Today''s day is' ,lv_day_switch, 'with switch keyword in new ABAP'.
Output :
No comments:
Post a Comment