Containers vs. Non-containers

For ease of use, Visual FoxPro allows you to define child object properties (using the WITH clause of ADD OBJECT) and object code (ex. FUNCTION Command1.Click) within a container class. However, you shouldn't do it if you plan to reuse the added object. The following example demonstrates the reusability problem:


DEFINE CLASS MyForm AS Form
Caption="My Form"
ADD OBJECT cmdButton AS CommandButton WITH ; Caption="Not reusable"
FUNCTION cmdButton.Click
WAIT WINDOW ; "Not reusable in other classes or subclasses"
RETURN
ENDFUNC
ENDDEFINE

Now if you want to build another form, you can't reuse the implicit CommandButton subclass embedded within my MyForm class. If you were to generate code from a Visual FoxPro SCX which was built using the Form Designer, the code would also look like this. Essentially, the Form Designer is a tool to implement a single form or formset container class. The key is to avoid this technique if you plan to reuse the child objects. For example, you can't reuse a CommandButton which sits on a form (SCX) in the Form Designer. You must first save it as a class or define it as an independent class. The proper object-oriented way to do the above example is as follows:


DEFINE CLASS MyForm AS Form
Caption="My Form"
ADD OBJECT cmdButton AS MyCommandButton
ENDDEFINE
DEFINE CLASS MyCommandButton AS CommandButton
Caption="Reusable"
FUNCTION Click
WAIT WINDOW ; "Reusable in other classes or subclasses"
RETURN
ENDFUNC
ENDDEFINE

Now you can use the MyCommandButton class in other classes or subclass it.