Android Question Another wary to call Subs

antonomase

Active Member
Licensed User
Longtime User
Hi,

I try to segment my code between views and operational functions.

By example :
B4X:
Main
Sub Globals
  dim btn1, btn2 as Button
  dim manager as ScoreManager
end sub
Sub Init
  manager.Initialize
end sub

Sub btn1_click
  manager.IncrementScore
end sub

Sub btn2_click
 ...
end sub

Class ScoreManager
Sub Class_Globals
 Sub tim as Timer
end sub

Sub Initialize
  ...
End Sub

Sub IncrementScore
 If tim.Enabled then
 ...
else
  ...
End if
End Sub

But sometime the class ScoreManager must have access to subs in the main code
B4X:
Class ScoreManager
Sub IncrementScore
 If tim.Enabled then
   CallSub(Main, "btn2_click")
else
...
End if

Is it the only possibility to call a sub in the Main code ? Does a syntax exist which allow to call the sub directly ?

Thanks
 

antonomase

Active Member
Licensed User
Longtime User
The problem is for lisibility and maintenance.
It is more clear to read Main.btn2_click than CallSub(Main, "btn2_click")
And if one day btn2_click becomes btn3_click, the error will not be detected on compilation.

I have some classes and they call each other. But I don't know how to manage these function in the Main code
 
Upvote 0

thedesolatesoul

Expert
Licensed User
Longtime User
In that case, I would do it differently.

In the class initialize, create something like
Sub Initialize(pModule as Object, pEventname as String)

and then assign them to local class variables (mModule, mEventname).

Later when you need to call the main activity, do:
CallSub(mModule, mEventname)

Then in the Main activity,
have the event as a sub:

Sub clsManager_Update
btn3_Click
End Sub


This way, all the view or dependent logic is still inside the activity, and the class can be reusable.

You can have a look at some examples of classes on the forums.
 
Upvote 0
Top