C++ – Avoid having an initialization method

cdesigndesign-patterns

I have this existing code where they have a class and an initialization method in that class. It is expected that once the object of the class is created, they need to call initialize on it.

Reason why the initialize method exist
The object gets created early to have a global scope and then the initialize method gets called later after loading a dll which it depends on.

Issue with having the initialize
The class now has this bool isInitialized which needs to be checked in every method before it proceeds and returns error if it is not initialized. Simply put, it is a big pain.

One possible solution
Initialize in the constructor.
Have just a pointer to the object in the global scope.
Create the actual object after the dll is loaded.

Issue with the above solution
Anyone who creates an object of this class needs to know that it needs to be created only after the dll is loaded or else it will fail.

Is this acceptable?

Best Answer

Sounds like a work for a virtual proxy.

You could create a virtual proxy containing a reference to the object in question. While the DLL is no loaded, the Proxy could offer certain default behavior to clients, once the DLL is loaded, the proxy will simply forward all requests to the real subject.

The virtual proxy will be responsible for checking the DLL initialization and based on this decides if the request should be delegated to the real subject.

Proxy Pattern in Wikipedia

How do you like this idea?

Related Topic