4 | Object Initialization and Cleanup
fore, it is vitally important to come up with a way to reliably supply the object's
attributes with data. Otherwise, you end up back in a procedural mode where
each method has to receive data via parameters or derive it from an external data
source (e.g., a database lookup, etc.). In either of
these
cases, the method becomes
more complex because you have to validate and perhaps derive data before you
can do any useful work.
Obviously, you want to avoid this kind of situation. However, to do so, you must
figure out a way to guarantee that the attributes of
a
class are properly initialized
before any calls are made to methods that depend on these attributes. Of course,
we could try to be disciplined in our approach and make sure that we call all of
the appropriate setter methods before using the object, but then we have to
remember to do it eveiy time an object is instantiated. In the best case, a lot of
redundant code is introduced. In the worst case, forgetting to call a method here
and there creates an even bigger problem by making it more difficult to figure out
where things went wrong. Clearly, we need a better method for initializing
objects.
Normally, whenever you declare a variable in an ABAP program, you don't have
to worry about creating it at runtime because this is handled for you automatically
by the ABAP runtime environment. For example, if you declare a global variable
in a program using a structure data type, you can immediately begin assigning
values to the components of that structure without having to issue a
CREATE
state-
ment. and so on. As you have seen, this is not the case for anonymous data
objects such as object instances. Here, we must use the
CREATE OBJECT
statement
to request that an object be created dynamically by the ABAP runtime environ-
ment. Prior to that request, we cannot use object reference variables in our pro-
gram because they do not point to a valid object instance.
One of the benefits of this kind of indirection is that it lets the ABAP runtime
environment take complete control of the creation process. Class developers are
allowed to interact with this process by creating a special method called a con-
structor. Constructors are called automatically by the ABAP runtime environment
after the object has been created but before control is returned to the program.
Inside the constructor, you can initialize all of the attributes in your class to
ensure that the object is created in a valid state.
Constructors are defined using a similar syntax to the one thatyou have used to
define normal methods in a class (see Listing 4.2). The only restriction here is that
112