I’m wondering what the standards are for accessing a child components control properties.
For example, I have my main form, which creates a child window that has a label. Using Delphi it’s possible to just do ChildForm.Label.Caption := ‘text’, however that just feels wrong to me for some unknown reason. The other way to set the text would be to set up a property for ChildForm that when set calls a method that updates the label caption.
Is there any reason why I should be doing this one way or the other?
There are four possibilities that come to mind:
a: direct access to child form’s components anfd their properties, as
you suggest
Plus: quick and easy. Minus: Your child form’s “internals” are unnecessarily exposed to the outside world, and your calling code can become more brittle as a result.
b: Access via a new published property of the child form
Plus: useful if you want to be able to set the property easily via the IDE form designer. Better encapsulation that ‘a’ above. Minus: Probably my least favourite approach, but I can’t explain exactly why. Properties are powerful, but all the stuff that happens under the covers just worries me a bit
c: Access via a child form setter method
Plus: simpler than B, but with the same improved encapsulation, and (to my mind) a slightly cleaner feel.
In many cases, you just want to be able to customize a form slightly when you create it. In this case, adding a parameter to the constructor is the easiest way. It saves you worrying about the ‘readable’ nature of the property, and the caption becomes fixed (as far as the outside world is concerned) at form creation, which may be helpful.
Plus: Saves bother of additional property or method. Minus: Not applicable in all cases.