Android Question Best coding

yfleury

Active Member
Licensed User
Hi all!

What is the best code between to code bellow to insert data in DB
I have to dim many variables. I want to know if it's better to dim variables outside the for next loop and affecting variable inside for next like this
B4X:
   dim name1 as string
   dim name2 as int
   dim name3 as double
   dim sqlRequest as string
for x=0 to field.size-1
   name1="blalba"
   name2=112345
   name3=1.12345
   sqlRequest="insert into .... blabla
   blabla
   ...
next
Or redim inside the for next like this

B4X:
for x=0 to field.size-1
   dim name1 as string="blalba"
   dim name2 as int=112345
   dim name3 as double=1.12345
   dim sqlRequest as string
   sqlRequest="insert into .... blabla
   blabla
   ...
next
I just want to have the best coding practice

Note: the code is only to illustrade my idea.
 

rraswisak

Active Member
Licensed User
in my opinion, if you just want to reuse (temporary) variable to hold value for query statement then i would recommend to declare out-side of looping, make sure using begintransaction and commit before and after looping
 

yfleury

Active Member
Licensed User
Thanks all It's appreciate for tip... So I am on good way without rewrite my code.
 

agraham

Expert
Licensed User
B4X only has two scopes for variables, global and local. It doesn't matter where in the Sub a variable is Dimmed, its actual declaration will be hoisted to the start of the Sub and it will be visible anywhere in the Sub.

For primitive types if doesn't really matter if you Dim them within the loop or outside, although each Dim will reset the variable to its default value, such as 0 for an Int or an empty string for a String unless you also do an assignment to that variable.

However for reference types there is a(n often not-so) subtle difference depending on the position of any Dim statement that can trip you up. Whenever you Dim a reference type the variable is assigned a new instance of that type so if you Dim it once outside the loop and use it inside the loop every pass round the loop will manipulate the same object. If you Dim it inside the loop a new instance is created for each pass round the loop. This is important if you want to save such instances each time round the loop when you must Dim inside the loop otherwise you will end up with only a single instance of that type, though perhaps saved in multiple places, that reflects the values given it in the last pass round the loop. Hint - if it needs Initialize called on it it is a reference type.
 
Last edited:

mcqueccu

Active Member
Licensed User
Depends on what you will be using your variable for, it can be Declared outside the loop or inside the loop.

Outside the loop if you will perform some operation on the variable - example you are receiving some values from DB and you need to sum them to a variable


Declaring inside the loop will reset variable everytime
 
Top