Is there a ternary or conditional operator available in the ABAP syntax? I haven't found one so am assuming that the answer is no but is there then an alternative that I can use to clear up the common "dumb" IF
statements that I routinely use?
For example, consider a method that logs a message with optional message parameters. To decide between using the imported parameter or the default I have to check the value like so:
IF iv_class IS INITIAL.
lv_message_class = 'DEFAULT'.
ELSE.
lv_message_class = iv_class.
ENDIF.
IF iv_number IS INITIAL.
lv_message_number = '000'.
ELSE.
lv_message_number = iv_number.
ENDIF.
IF iv_type IS INITIAL.
lv_message_type = 'E'.
ELSE.
lv_message_type = iv_type.
ENDIF.
A ternary operator would reduce each of these five-line statements to a single line as seen in the below code block. It could even make the use of a temporary variable unnecessary when the operator is used in-line.
lv_message_class = iv_class IS INITIAL ? 'DEFAULT' : iv_class.
lv_message_number = iv_number IS INITIAL ? '000' : iv_number .
lv_message_type = iv_type IS INITIAL ? 'E' : iv_type .
Is there a way to approximate this kind of programming style in ABAP or am I stuck with the clutter?
Release 7.40 brings a whole bunch of ABAP improvements which I'm finding heaps interesting. The ternary style declaration (at least something that resembles it) is one of them
Syntax:
COND dtype|#( WHEN log_exp1 THEN result1
[ WHEN log_exp2 THEN result2 ]
...
[ ELSE resultn ] ) ...
Example data declaration of a variable called 'bool' and a conditional value assignment in one line. Old skool ABAP this will take like 10 lines.
DATA(bool) = COND #( WHEN i * i > number THEN abap_true ELSE abap_false ).
More info: http://scn.sap.com/community/abap/blog/2013/07/22/abap-news-for-release-740
No, in ABAP there is no operator similar to the construct a ? b : c
known from other languages. In your concrete example, however, you could declare default values for your method parameters iv_class
etc. in the method's signature.
While declaring the variables you can set the default value or explicitly do the same as below.
lv_message_class = 'DEFAULT'.
lv_message_number = '000'.
lv_message_type = 'E'.
IF iv_class IS NOT INITIAL.
lv_message_class = iv_class.
ENDIF.
IF iv_number IS NOT INITIAL.
lv_message_number = iv_number.
ENDIF.
IF iv_type IS NOT INITIAL.
lv_message_type = iv_type.
ENDIF.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With