Code Behind Forms

In traditional Visual Basic applications, most programs have tended to respond to the events caused by the user - through the forms and controls that we've provided on our forms. So it's been very common to find the code to handle these events directly behind the controls that raise them.

Many developers have therefore written the bulk of their code in the subroutines that run when particular events fire:

Private Sub cmdButton_Click()
  ' do all the work here
End Sub

Meanwhile, other developers have tended to call centralised subroutines in the module's General section, or subroutines that have been placed in a separate code module:

Private Sub cmdButton_Click()
  DoWork()
End Sub

Private Sub DoWork()
  ' do all the work here
End Sub

Either way, the results have been the same: Visual Basic code has been directly invoked by the events raised in the user-interface (UI).

Putting code behind events from the UI hasn't provided us with much in the way of code reuse. The most that we've been able to hope for is to use code modules - so that we can call our code from multiple forms.

To use code in other projects, we've had to copy original code into our new projects, causing duplicate code and maintenance problems down the line. Another approach has been to include the same code module in multiple projects; but then we run the risk that modifying the code in the module will break any other programs that rely on the module. Even if we don't break the programs, they need to be recompiled and redistributed to take advantage of our changes.

By designing our applications with business objects and components, we now have the opportunity to make it significantly easier to reuse our code. Instead of trying to reuse source code, we can package that code into binary components and use those components anywhere we need them.

If we create a component that provides some key functionality - everything to do with our customers, for instance - then we can use that component in any program that needs to deal with customers. As long as we are careful not to change or remove any properties or methods from our objects, we can change or add anything we want to our customer component with little risk of breaking existing programs.

© 1997 by Wrox Press. All rights reserved.