7

Are there any existing methods or function modules that flip boolean values efficiently?

I've come up with a simple implementation should I have to define my own utility method, but I'm wondering if this is the most efficient approach:

IF iv_bool = abap_true.
    rt_bool = abap_false.
ELSEIF iv_bool = abap_false.
    rt_bool = abap_true.
ELSE.
    rt_bool = abap_undefined.
ENDIF.

EDIT: As mentioned by Smigs, this implementation flips three-valued booleans or "trileans"

Sandra Rossi
  • 11,934
  • 5
  • 22
  • 48
Lilienthal
  • 4,327
  • 13
  • 52
  • 88
  • 2
    If you need to deal with abap_undefined, then it's not a boolean you're using but a tri-state; and what you've posted is probably the most efficient way. I'd try and avoid having to use abap_undefined - remember that the default value of a variable with type abap_bool will be abap_false. – Smigs Apr 24 '14 at 15:35

2 Answers2

17
rt_bool = boolc( iv_bool <> abap_true ).

will flip a boolean. However, it wouldn't deal with abap_undefined.

From 740 SP08 onwards, you can use xsdbool( ) instead of boolc( ) to achieve the same result. There is no difference for the example given, but xsdbool( ) is safer when using in comparisons

Smigs
  • 2,362
  • 1
  • 21
  • 24
  • And a real boolean flip shouldn't, as mentioned by Smigs, so this is perfect. If "trilean" support is needed a check for `abap_undefined` can be added at the cost of performance. – Lilienthal Apr 25 '14 at 08:14
  • 2
    Starting with ABAP 7.4 SP 08 there is a new boolean function `xsdbool`. It should generally replace `boolc` because the latter has a [known issue when comparing to `abap_false`](http://scn.sap.com/community/abap/blog/2014/09/29/abap-news-for-740-sp08--logical-expressions): `boolc( 1 = 2 ) = abap_false` evaluates to false due to string-character comparison. – Lilienthal May 22 '15 at 09:12
  • 1
    I've edited the answer to include information about `xsdbool( )`. Since the question is just about flipping booleans, it's still safe to use `boolc( )`; you wouldn't typically flip a boolean just to then compare it to `abap_false` on the same line! – Smigs May 22 '15 at 09:31
  • Very true, I just wanted to add the caveat since I only just discovered its nasty bug potential. Thanks for updating the answer. – Lilienthal May 22 '15 at 09:35
0

Just put a "not" before the condition:

rv_bool = xsdbool( not ( a = b and c = d ) ).

There is no need for workarounds. You can code it straight on.