Modules, classes & object lifetime
Separate stateless helpers from instance state, and keep object ownership visible.
Choose a home for behavior#
| Document | Good responsibility |
|---|---|
| Form | Events and state belonging to one window |
| Standard module | Reusable calculations and transformations |
| Class module | State and operations belonging to one created instance |
| UserControl | Reusable visual composition with an explicit public contract |
Moving code into a module does not automatically make it reusable. Remove accidental dependencies on particular Form controls and pass the values the operation needs.
A complete stateful class#
The project declares Counter.cls as a class module. Each New Counter gets its own mValue. The read-only property exposes a result without letting callers assign the field directly.
Option Explicit
Private mValue As Long
Public Property Get Value() As Long
Value = mValue
End Property
Public Sub Add(ByVal amount As Long)
mValue = mValue + amount
End SubCreate a reference before using it#
Public Sub TryCounter()
Dim counter As Counter
Set counter = New Counter
counter.Add 3
counter.Add 2
Debug.Print counter.Value
End SubThe output is 5. Dim declares the reference; New creates an instance; Set assigns that reference. Use Nothing for an empty reference and Is to compare identity. Assign ordinary values with =.
A variable is not an ownership policy#
A reference remaining in a variable does not guarantee that its window or service is still usable. A closed Form is not automatically a fresh Form. A database connection needs an explicit close path. A component’s work must stop when its owning lifetime ends.
Use Form lifetime for windows and SDK lifecycle for components. Avoid an indefinitely retained global reference just to keep a temporary window reachable.
Test two instances#
Create two Counter instances, add to one and verify the other stays at zero. Apply the same test to a reusable visual component. The CustomerCard consumer exercises the package boundary instead of compiling the authoring source into the consuming app.
20f4bfed6b · Build manifestSources & maintenance
Original web explanation, reviewed against these repository sources. API tables and example files follow the implementation.
docs/manual/21-language-reference.mddocs/manual/11-language-toolkit.mdsite/examples/LanguageWorkbench/Main.bassite/examples/LanguageWorkbench/Counter.clsdocs/manual/09-code-organization.md