Stringification

String handling in Delphi has always been quick, but this has lead to the abuse of the data type.  I have seen code where strings are used to store all kinds of data (ie: Float) and is continually converted back and forth depending on whether it’s needed for the UI, a calculation, or to generate dynamic SQL.  Whenever data is stringified, it is open to interpretation by all consumers of that data.  Should it be handled as a string or converted to another data type and if so what type with what kind of precision and scale is necessary to avoid loss?  Who is responsible for conversion (the caller or the callee)?

By not using the native type for a given piece of data it becomes unclear as to how the data should be transformed in order for it to be stored for example to disk in the form of a config file entry, or used as a string in a SQL clause built using the Format() function.  Environmentally sensitive functions like Format() can cause massive code breakage when the user changes for example the decimal separator character, resulting in invalid SQL statements being generated.

The identifier name used for fields or variables representing data from a database column may be re-used to identify the stringified fields, causing confusion and compilation errors over the data type differences if hungarian or some other notation is not used as part of variable names.

Once data is stringified, there is no longer a data contract, and what ensues is a lot of wet (aka not DRY) brittle code (repeated data conversions) thrown together in a haphazard fashion in an effort to just “make it work”.  Making little changes like supporting different locales with say a comma instead of a decimal point for float values becomes a painful experiment if the applications are not properly layered.

My advice; write true native code, keeping fields and variables in their native type, and avoid stringification as much as possible.

Leave a Reply