14.01.2020 Views

ABAP_to_the_Future

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Implementing Mock Objects 3.2

rd_answer = 'Y'.

ENDMETHOD. "mock user interface implementation

METHOD fire_missile. "Mock External Interface Implementation

* Don't do ANYTHING - it's just a test

ENDMETHOD. "Fire Missile - Mock Ext Interface - Implementation

Listing 3.3 Mock Method Redefinitions of Assorted Real Methods

In this example, you create subclasses of your database a ccess class, your user

interface class, and your external system interface class. Then, you redefine the

methods in the subclasses such that they either do nothing at all or return some

hard-coded values.

Object-Oriented Recommendation

In order to follow one of the core OO recommendations—to favor composition over

inheritance—you should have created an interface that is used by your real database

access class and also have the mock class be a subclass that implements that interface.

In the latter case, however, you have to create blank implementations for the methods

you are not going to use, and that could be viewed as extra effort. Nevertheless, interfaces

are a really Good Thing and actually saveyou effort in the long run. Once you read

books like Head First Design Patterns (see the “Recommended Reading” box at the end

of the chapter), you will wonder how you ever lived without them.

3.2.2 Injection

Usually, classes in your program make use of smaller classes that perform specialized

functions. The normal way to set this up is to have those helper classes as private

instance variables of the main class, as shown in Listing 3.4.

CLASS lcl_monster_simulator DEFINITION.

PRIVATE SECTION.

DATA:

"Helper class for database access

mo_pers_layer TYPE REF TO ycl_monster_pers_layer,

"Helper class for logging

mo_logger TYPE REF TO ycl_logger.

ENDCLASS.

Listing 3.4 Helper Classes as Private Instance Variables of the Main Class

145

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

Saved successfully!

Ooh no, something went wrong!