Delphi - Running code without showing form
What do you think about this programming practice: - I need to execute one transaction at first form and after that to force some updates that are placed at another form (for each item that is shown at another form). I.e. it would be like show that form and click at some button. Because it is mandatory to execute these functionalities from second form, I thought to do it without showing second form. Is that good 开发者_高级运维programming practice or you have some other recommendation?
Also, is it enough just to set property> Visible:=False before ShowModal for the second form or I need to do some other actions?
Well, it's unusual to have a form that you don't show. Normally you separate your business logic from the UI.
To answer your question, I don't think you need to call ShowModal at all. Just define a method on the form class and call that. Ultimately forms are just Delphi objects and you can use them as such. If you don't want to show them, don't call ShowModal or Show.
Second question first: Setting Visible := False
is of no benefit because the point of all ShowXXX methods is to make the form visible. As David says, you could perform the actions without calling Show at all, provided of course your form doesn't rely on any OnActivate
or OnShow
code in order to do it's job properly.
As for whether this is a good idea, I say no!
- As I've already pointed out there is a concern you have to watch out for. I.e. that currently (or even due to maintenance at some point in the future) your form relies on being visible to do its job properly.
- Of course, you could work around that by letting the form flicker open, and be programatically closed. Clearly an aesthetically poor choice.
- Not to mention the problems of getting it right. You'll end up writing a bunch of patch-work code to wrap the form so that it can do what you need to do, when you should rather do the following...
Correct Approach
- Your form is currently doing at least 2 distinct things:
- Visual UI control (call it A)
- and "mandatory functionalities" (call it B)
- It doesn't matter much whether B is doing validation rules, extra processing, or whatever.
- B is a process that does not require user interaction.
- Therefore, you need to:
- Copy B into a non-UI location (either a simple unit with a custom object or a data module). Call it B*
- Modify the form to call B* instead of using B.
- Test that your form still behaves correctly.
- Delete B
- And now you can have your new form call B* instead.
The above approach will save you huge headaches in the future.
精彩评论