I use the type pool ABAP
and its constants in coding. It should always be available, though you may have to include it manually on older systems. For dictionary elements, I prefer to create my own data elements using any of the default domains so that I can add descriptions to suit my needs. You can use WDY_BOOLEAN as well.
Preferred Boolean type for ABAP Development
-
13-06-2023 - |
Question
SAP doesn't have a core Data Type for boolean values. Additionally, higher level boolean types in SAP typically have three states: true ('X'), false (' ') and unknown ('-').
Now obviously booleans are a cornerstone of a lot of my development work but I realised that I haven't been terribly consistent in my type (data element) usage. So far I believe these are the most common:
abap_bool
: defined in the abap type-pool, unconstrained but constants are defined for true, false, unknown, yes and noos_boolean
: data element, Yes ('X') or No (' ')xfeld
: data element, True ('X') or False (' '), lacks a field label, described as a checkbox
In my code I've mainly used abap_bool
as I can then work with constants instead of character values, not that I couldn't assign abap_true
to an xfeld
. However, I've been cautioned that this type pool might not always be available.
I'm now wondering about the best practices for boolean values, specifically:
- Is there a preferred type that I should use?
- Will using the abap type-pool cause issues in certain modules or scenarios?
- Does the possibility of abap_bool containing an unknown or indeed any character value matter?
Solution
OTHER TIPS
According to rule 6.11 of the Official ABAP Programming Guidelines, you should use abap_bool.
Rule 6.11: Use the abap_bool Data Type for Truth Values
To explicitly handle truth values, use the abap_bool type as a workaround for a real Boolean data type. A data object that is declared in this way is not supposed to contain other values than the corresponding constants, abap_true and abap_false (as well as abap_undefined).
Update for Release 7.40, SP08:
With Release 7.40, SP08 you get the Predicative Method Calls and you can code something like:
IF cl_abap_demo_services=>is_production_system( ). "There is no '= abap_true' needed!
cl_demo_output=>display(
'This demo cannot be executed in a production system' ).
LEAVE PROGRAM.
ENDIF.
Your method (in the example is_production_system
) must return a ABAP_BOOL-value (abap_true ('X') or abap_false (' '))
The online help has an example.
Sadly, this is the bane of ABAP... not having a fundamental boolean type... only boolean expressions. So the wonderful thing in ABAP is that there are so many boolean types to choose from!
After many years I believe the best way is to just roll your own (sadly). If you do class-based development, then always just add a true
and false
(and undefined
if you wish) constants in your base class, and define your own boolean and/or boolean_undefined types.