There are times that you need to keep track of user response (e.g. score) and based on that determine if falls within certain range (e.g. min / max score) and then provide a result (e.g. grade). For example, based on below data, if user response is 85, his grade would B.
Approach 1 – A simple approach would be to create a if-then-else blocks that includes hard-coded data and the related grade (see below). However, here are some disadvantageous of this approach:
- Long list of if-then-else
- Hard-coded data
- Possible blocks performance issues
- Difficult to maintain (e.g. you want to add some additional condition in between; e.g. 70 to 75 would be C- and 76 to 79 a C+
Approach 2 –An alternative would be to create a data structure (List) that contains your data. Next, create a procedure that loops through the List and checks data. The procedure below (checkResponse) uses a for-loop to loop through each row of our list (scores). For each row, it splits that row into a List. For example, it converts 90,100,A into a List. It next checks to see if user-response falls within index 1 (min) and index 2 (max) of the list. If so, it prints index 3 (grade).
Above reduces the number of blocks that were used in Approach 1. It provides ability to add items to the list WITHOUT affecting the logic of the procedure. However, data is still hard-coded. Let’s say that we want to include ability to retrieve data from server and then have the logic use the new data WITHOUT updating code! This could be accomplished using Approach3 below:
Approach 3 – This approach will take 2nd approach a bit further and will make it one-step closer to remove the hard-coding of data. For example, let’s say that you have published your app. After sometime, you wish to change the scores; for example change 70,79,C as follows:
- Score of 70 to 75 would be C-
- Score of 76 to 79 would be C+
To make this happen, instead of initializing our data structure (global variable “scores”) with “make a list” in Approach 2, we create a procedure that splits a long text data by certain delimiters. Once split, we set that into our List data structure like below.
Where does the dynamic portion come in? This can be simply done using Web component that on application start-up, retrieves data from the server (as text) and then invokes the loadScores procedure once data is returned from server.