Android Question Class_Globals vs Initialize

Alessandro71

Well-Known Member
Licensed User
Longtime User
A variable initialization in a Class_Globals gets executed when Initialize is called.
What is the difference between initializing variables in Class_Globals vs in Initialize?

B4X:
Sub Class_Globals
    Private test as boolean = true
End Sub
 

LucaMs

Expert
Licensed User
Longtime User
A variable initialization in a Class_Globals gets executed when Initialize is called.
If so, it should be the same, but...

Since I have:
Sub Class_Globals
and
Sub Initialize

WHY NOT initialize EVERYTHING in the Initialize?
I can mix a fruit salad in the bathroom (Class_Globals), but why not in the kitchen (Sub Initialize)?!

Why complicate your life when it's already complicated enough?
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
Possibly the logic that in Class_Globals you set the value that you want it to start with, irrespective of who creates it. Whereas in Initialize, it sets the value to what the caller wants (like a name or address field).
 
Upvote 0

Alessandro71

Well-Known Member
Licensed User
Longtime User
Possibly the logic that in Class_Globals you set the value that you want it to start with, irrespective of who creates it. Whereas in Initialize, it sets the value to what the caller wants (like a name or address field).
that's a valid use case: Initialize can have parameters, while Class_Globals is static
 
Upvote 0

stevel05

Expert
Licensed User
Longtime User
There is a difference between assigning a value to a variable and initializing a variable. The Globals subs (class or otherwise) should only be used for simple assignments, where as in the initialize sub, you can do more complex assignments and initializations:

B4X:
Sub Class_Globals
    Private test As Boolean = True
    Private Count As Int = 0
    Private MaxCount As Int
    Private MyList As List
End Sub

Sub Initialize
    MyList.Initialize
    MyList.AddAll(Array As String("First", "Second"))
    MaxCount = CountElements

End Sub

Sub CountElements As Int
    Return MyList.Size
End Sub

An over simplified example.
 
Upvote 0
Top