14.01.2020 Views

ABAP_to_the_Future

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Design by Contract 7.3

automatically call the clas s invariant and raise an exception if the kitchen had

gone up in flames.

Turning to implementing class invarian ts using ABAP, you cannot achieve the

same functionality that exists in Eiffel (c alling the same test automatically at the

end of every method) directly in ABAP, but you can come close.

Coding a class invariant involves using the standard SAP interface IF_CONSTRAINT

(originally discussed in Chapter 3), which lets you create quite complicated check

routines. To demonstrate this, turn once again to the monster example. You want

to make sure that after every method call to your monster, it still remains a monster,

rather than turning into a fluffy pink bunny or some such (let’s agree, fluffy

pink things are not scary).

The example code is shown in Listing 7.13. First, im port the instance of your

monster class. The constraint interface takes a data object as input, so you need to

cast that into a local variable represen ting the monster object before you can

check the data. Presume failure, and then run a series of tests on the various attributes

of the monster to make sure it has not turned pink or gone all fluffy. If all

the tests are passed, then the monster is judged not pink and not fluffy, and you

return a TRUE value to indicate that the method call has not ruined the essential

nature of the monster.

The get description method also has to be implemented to describe what has

happened in the event of a failure of the various tests (e.g., in this case, the monster

is no longer a monster).

CLASS lcl_monster_constraint DEFINITION.

PUBLIC SECTION.

INTERFACES if_constraint.

ENDCLASS. "Monster Constraint Definition

CLASS lcl_monster_constraint IMPLEMENTATION.

METHOD if_constraint~is_valid.

*-------------------------------------------------------*

* IMPORTING data_object TYPE data

* RETURNING result TYPE abap_bool

*-------------------------------------------------------*

* Local Variables

DATA: lo_monster TYPE REF TO ycl_monster.

279

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!