In the last post we started discussing selection forms and I stopped at the point where we were encountered a dilemma: the form is constructed with the form.Create() method but there’s data that’s not loaded into it yet. So how do you get the data into the form?
I’d like to take a slight detour for a minute and discuss something called dependency injection. Wikipedia defines dependency injection thusly:
Dependency injection is a software design pattern in which one or more dependencies (or services) are injected, or passed by reference, into a dependent object (or client) and are made part of the client’s state.
Any time you need to pass data into an object, it represents this design pattern. Some folks might quibble about whether the dependencies can only be “services”, or whether they need to be “passed by reference”. For this discussion, it doesn’t really matter — the point is, you have some data (fields, objects, or services) that needs to be injected into the object (a TForm in this case) and it affects the state of that object. When a form opens and you want the user to be looking at a bunch of fields already populated with data to select from, that is the initial state of the form.
So the question is, what’s the proper way of interacting with the form so it is initialized properly when the user sees it? Let’s look at our options within the context of the dependency injection pattern. Continue reading