Quote:
Originally Posted by ownedbycats
Which of these is better practice?
|
It depends.
The underlying problem is the same as you solve with check_yes_no(), what to do with undefined values. What do you want to happen in this case? Is 'undefined' the same as '0'? Is it something else? If defined, what comparisons are needed?
For integers the field() function returns the empty string if the book's value is not defined, otherwise (as you said) the formatted value. If undefined is to be treated as zero and you aren't doing any non-equal comparisons then you need
Code:
v = field('#percentread');
if !v || v == '0%' then
With raw_field() you have the choice of what is returned for undefined values. For example:
- x is undefined: raw_field(x) returns 'none'
- x is undefined: raw_field(x, 0) returns 0 (zero)
- x is undefined: raw_field(x, -1000) returns -1000
- x is undefined: raw_field(x, '') returns the empty string
- x is undefined: raw_field(x, 'twas brillig') returns the string 'twas brillig'
- x is defined: all the above raw_field() examples return x unformatted.
In the end, what you do is a matter of personal preference. You must understand what the code does for the possible range of values. You must be able to maintain it, which means understanding the code again in the future.
My preference is to use raw_field, setting the default to what makes sense in the context. That isolates me from the vagaries of formatting (which can change) and lets me use non-identical comparisons without thinking too much about it. If we assume that undefined values are to be treated as zero then this:
Code:
v = raw_field('lookup key', 0)
if v ==# 0 then
If later I look at this code then it is easy for me to know that the field is numeric and undefined values are assumed to be zero. It will work if later I decide that I want decimal percentages, e.g., 43.5% or 0.0%.
And yes, I know I get rather pedantic.