zl程序教程

您现在的位置是:首页 >  前端

当前栏目

A code refacting using string template

code string Using Template
2023-09-14 09:02:51 时间

Created by Jerry Wang, last modified on Jun 23, 2016

The original code before refact:
There are some fields in DDIC structure CRMT_SMS_STATUS_KEY which could be used for deletion.
Currently three fields are supported: sms_uuid, phone_number and resend_times.
Current implementation is to evaluate all possible status of the three fields, whether they are intial or not.
In theory support you have n fields to support for deletion case the combination would be . If we still follow the current design, the code could not be sustainable: more and more IF … ELSEIF has to be added.
image

A better solution could be using string template instead. A draft code looks like below:

FORM delete USING is_status_key TYPE CRMT_SMS_STATUS_KEY.
  data: lv_statement TYPE string.
  CHECK is_status_key-sms_uuid IS NOT INITIAL.
  lv_statement = | SMS_UUID EQ '{ IS_STATUS_KEY-SMS_UUID }' |.
  IF is_status_key-phone_number IS NOT INITIAL.
     lv_statement = lv_statement && | AND phone_number = '{ is_status_key-phone_number }'|.
  ENDIF.
  IF is_status_key-resend_times IS NOT INITIAL.
     lv_statement = lv_statement && | AND resend_times = '{ is_status_key-resend_times }'|.
  ENDIF.
  " IF is_status_key-XXXX IS NOT INITIAL.
  "    lv_statement = lv_statement && | AND XXXX = '{ is_status_key-XXXX }'|.
  " ENDIF.
TRY.
    DELETE FROM crmd_sms_status WHERE (lv_statement).
  CATCH cx_root INTO DATA(cx_root).
    "" DO ERROR HANDLING HERE
  ENDTRY.
ENDFORM.

The advantage is, if more fields are to be supported, you could simply add the code marked with bold, without having to code complex IF… ELSEIF statement. However, since now we use dynamical SQL statement instead, make sure to avoid the potential SQL injection by escaping all input fields of CRMT_SMS_STATUS_KEY via method cl_abap_dyn_prg=>escape_quotes.