banner 728x90

Variables declared in a Loop

In Mobile Web Development 40 views
banner 728x90

Ran into a very subtle issue today with variables declared in a loop. For pcreminder.com, I have an outer loop that gets all the reminders that need to be sent for all users. Within that loop, there is a second loop that loops through all the receipts for the reminder and sends the actual reminder. I have a reminder counter that keeps track of the number of reminders sent so that I can update the users count for the month. Let’s look at a very simplified version of this code:

2014-12-31_0907

So as you see in the above example, I have 20 reminders to send. Each reminder has 10 recipients.

Now for a Pop Quiz: Assuming that each reminder is for a separate user, how many reminders will each user be charged for?

If you answered 10, you were wrong!

The first user will be charge with 10, the second with 20, the third with 30, etc. Let’s take a look at the trace window to confirm this:

2014-12-31_0911

Apparently WX doesn’t redeclare the variable with each loop, which makes sense as that could lead to a memory leak, however I was expecting it to be reinitialized. It is a simple fix all we need to do is change the declaration to also clear the variable, like this:

ReminderCount is int = 0

And now if you run the code the trace window looks like this:

2014-12-31_0914

So as you see, not a hard issue to fix, but if you are not careful with your coding, you can definitely get an unexpected result, like say a bunch of users complaining because they are getting “Over Your Limit” email messages!

Now, back to your regular schedule program….

banner 728x90
author
Author: 
    Script & Style Show: Episode 1: Marc Grabanski
    Script & Style Show: Episode 1: Marc Grabanski
    During this second episode of the Script
    AWS AppSync region expansion and new functions for API keys
    AWS AppSync region expansion and new functions for API keys
    AWS AppSync, a managed GraphQL service with
    What is the best time to involve your mobile app users?
    What is the best time to involve your mobile app users?
    When talking to customers about mobile analysis,
    How to make a Twitter bot with Node.js
    How to make a Twitter bot with Node.js
    Twitter bots have been in the news

    Leave a reply "Variables declared in a Loop"

    Must read×

    Top