McBasic™Get McBasic™ ↗
Build 881
Language reference

Modules, classes & object lifetime

Separate stateless helpers from instance state, and keep object ownership visible.

Choose a home for behavior#

DocumentGood responsibility
FormEvents and state belonging to one window
Standard moduleReusable calculations and transformations
Class moduleState and operations belonging to one created instance
UserControlReusable 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.

Counter.cls — complete class module
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 Sub

Create a reference before using it#

A complete procedure; requires the declared Counter class
Public Sub TryCounter()
    Dim counter As Counter
    Set counter = New Counter
    counter.Add 3
    counter.Add 2
    Debug.Print counter.Value
End Sub

The 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.

Source baseline 20f4bfed6b · Build manifest
Sources & maintenance

Original web explanation, reviewed against these repository sources. API tables and example files follow the implementation.

  • docs/manual/21-language-reference.md
  • docs/manual/11-language-toolkit.md
  • site/examples/LanguageWorkbench/Main.bas
  • site/examples/LanguageWorkbench/Counter.cls
  • docs/manual/09-code-organization.md