Taking Control of the Instantiation Process
Perhaps the best way to illustrate the utility of controlled instantiation is to look
at how it might be used in a practical example. Let's imagine that you want to
build a class library that can be used to process XML documents. To maximize the
usefulness of your XMLDocument class, you want to be able to load XML documents
from a number of different types of data sources. For instance, you might want to
build the XML document using a file, a byte stream, a tree-like data structure, and
so on.
In many object-oriented languages, this problem can be solved by overloading the
constructor method to support different method signatures. Here, each over-
loaded constructor method has the same name but a different set of parameters.
Unfortunately, this is not a feature supported in ABAP Objects. One common
workaround for this limitation is to create multiple optional parameters in the
constructor's method signature and try to figure out which scenarioyou are deal-
ing with inside the constructor's implementation using conditional logic. Listing
4.7 shows an IF statement that uses the IS SUPPLIED option to determine if
parameter lm_paraml was supplied to the method during the method call.
IF im_paraml IS SUPPLIEO.
ENDIF.
Listing 4.7 Determining if Parameters Are Passed in a Method Call
The problem with this technique is that the signature of the constructor method
becomes quite large and difficult to work with. The logic in the constructor code
also becomes obscured by all of the various input permutations.
As you have seen, our typical approach for dealing with complexity is to figure
out a way to encapsulate (or hide) it. In this case, we want to encapsulate the
instantiation process to make it more straightforward and intuitive. One way to
encapsulate this process is to configure the XML document class to have a pro-
tected/private instantiation context. This implies that users will no longer have
the ability to directly instantiate XML document objects. Instead, they must work
with public creational class methods that arc customized to build XML documents
using various types of inputs (see Listing 4.8). These methods behave like a con-
structor, taking control of the initialization process. This is important because the
primary goal here is to simplify the initialization process so that a single construc-
tor is not responsible for supporting all of the various initialization variants that
we want to provide.
119