Using Functional Methods in logical Expressions
7.02后在条件判断中引入了Functional Method,其返回一个特定的结果值。
IF strlen( string ) > 10.
"Do Something
ENDIF.
CHECK zcl_bc_system_environment=>is_production( ) = abap_false.
Omitting ABAP_TRUE
通常我们在IF条件中判断是否为TRUE IF zcl_bc_system_environment=>is_production( ) = abap_true.
。7.4开始,可以忽略ABAP_TRUE,直接IF zcl_bc_system_environment=>is_production( ).
。这种方式只在返回值为ABAP_BOOL类型时才有意义。比如方法返回值为NO,但其实认为的结果是not initial,将会认为是APAP_TRUE。
Using XSDBOOL as a Workaround for BOOLC
以前我们可以BOOLC判断true/false,但由于BOOLC返回的是string类型,而abap_ture是C类型,如果返回是abap_true那没问题,但如下代码,虽然boolc返回空,但因为是string类型,与abap_false不相等,因此会造成误解。
IF boolc( 1 = 2 ) = abap_false.
WRITE:/ '1 does not equal 2'.
ELSE.
WRITE:/ '1 equals 2, and the world is made of snow'.
ENDIF.
7.4后可以用XSDBOOL,将返回ABAP_BOOL类型,如下代码将正确执行。
IF xsdbool( 1 = 2 ) = abap_false.
WRITE:/ '1 does not equal 2'.
ELSE.
WRITE:/ '1 equals 2, and the world is made of snow'.
ENDIF.
The SWITCH Statement as a Replacement for CASE
我们经常见到如下代码,对一个变量进行条件赋值,在每一个条件WHEN中必选将该变量都写一遍。
DATA: indicator TYPE scal-indicator,
day TYPE c LENGTH 10,
date TYPE sy-datum.
date = sy-datum.
CALL FUNCTION 'DATE_COMPUTE_DAY'
EXPORTING
date = date
IMPORTING
day = indicator.
CASE indicator.
WHEN 1.
day = 'Monday'.
WHEN 2.
day = 'Tuesday'.
WHEN 3.
day = 'Wednesday'.
WHEN 4.
day = 'Thursday'.
WHEN 5.
day = 'Friday'.
WHEN 6.
day = 'Saturday'.
WHEN 7.
day = 'Sunday'.
WHEN OTHERS.
RAISE EXCEPTION TYPE zcx_monster_exceptions.
ENDCASE.
7.4后引入了SWITCH,这样就不需要每个条件分支中写入变量名了,对于day2类型的定义也移到了表达式中,减少了代码量。并且这里也可以用THROW来抛出异常。
DATA(day2) = SWITCH char10( 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 THROW zcx_monster_exceptions( ) ).
The COND Statement as a Replacement for IF/ELSE
CASE只能一次判断一个变量,如果条件多我们要用if/else来判断,7.4后引入了COND,如下代码,可以在WHEN分支中添加其他判断条件。
cs_monster_header-sanity_description =
COND text30(
WHEN cs_monster_header-sanity = 5 THEN 'VERY SANE'
WHEN cs_monster_header-sanity = 4 THEN 'SANE'
WHEN cs_monster_header-sanity = 3 THEN 'SLIGHTLY MAD'
WHEN cs_monster_header-sanity = 2 THEN 'VERY MAD'
WHEN cs_monster_header-sanity = 1 AND
day = 'Tuesday' THEN 'HAVING AN OFF DAY'
WHEN cs_monster_header-sanity = 1 THEN 'BONKERS'
ELSE 'RENAMES SAP PRODUCTS' ).