Tag: codeing tips
Easily changing option values on a field without breaking a sweat
by admin on dec.16, 2009, under Code
How many times have we built a table with option fields and then – six months later – had to insert option values between the existing option values?
After we insert a new option value, we have to find all code using the options and change the option references, because – as you know – it is the integer value of the option that gets compiled into the object and not the Option::Value part of the field.
Damn.. what can we do to avoid that?
The answer is pretty simple: Start using functions to return the values of the individual option values.
Let’s say we have a simple table with a option field with three values:
Option1, Option50 and Option100
Now, create three functions on the table, called:
GetOption1, GetOption50 and GetOption100
Set each function to return an integer. We will be using these functions to return the value of a specific option.
Now we are ready to use these new functions in our code:
It is important to use the GetOption-functions everytime and everywhere you would normally use the option value reference (the “incorrect” code).
Now comes the part that would usually make us sweat.
Some person says that he wants a new option value – called Option20 – and he wants it to be placed between Option1 and Option50 (can’t argue with that
))
As the nice guys we are, we say “ok, I will create your option for you”, knowing we have to go through days of code to find all the places we used Option50 and Option100, because their integer-value have now changed!
Well… that is no problem anymore
You’ve got the Option-functions to do the work.
Let’s insert the option value:
Now let us take a look at our table functions for the option field:
As we knew it would happen. The Option20-value is now taking the place of what used to be Option50’s integer value.
Well, that is ok, because we only need to update the code here in the table. And nowhere else !
Update your functions to look like this:
Now, let’s have a look at the code where we used the function:
Notice how the function-call has not been changed (obviously). But the Option-value reference has been changed, just as in our function, and this would have been the case perhaps hundreds of places around the system.
I have started to create return-functions for option values everytime I create a new option field and/or add or update values to it.
It is a relief only having to change the code one place