Code reuse has enormous benefits for maintenance and construction, but it presents developers with a trade-off between maintenance and performance. In this article, I'll present an approach that balances the two considerations.
When you need an expression (or formula) in many places in an application, there are too few choices for reusing it. You can copy it everywhere, but that makes maintenance and enhancement a problem. You can make a user-defined function (UDF) of it. That’s usually a good thing because you can document it. It also lets you refer to the formula by name, which can make the calling code easier to follow. But calling a UDF repeatedly can have a potentially serious performance impact. Some also argue that creating a UDF from an expression is overkill. Many developers opt to not reuse these bits of code, despite knowing how important reuse is.
A third option is to find some way to embed the expression where it's required. Formulas and expressions may not be the only thing inserted, so let's allow for something a little bigger and call them snippets.
A typical VFP expression
A pretty common need is to produce a string like "Yearwood, Mike". The formula for this is easy enough, but it must assume the table might be missing any combination of last and first name. It should also specify a length, especially when used in indexes and SQL commands. That length could vary as the formula is used in different parts of the application.
PADR(;
ALLTRIM(tsf_Last) ;
+ IIF(EMPTY(ALLTRIM(tsf_Last)) ;
+ OR EMPTY(ALLTRIM(tsf_First)),'',', ');
+ ALLTRIM(tsf_First),50)
A typical SQL expression
The expression itself might vary depending on the database server. This is possible in SQL Server, but not in VFP:
CAST(LTRIM(RTRIM(LAST_NAME)) +
CASE
WHEN
LEN(LTRIM(RTRIM(LAST_NAME))) = 0
OR LEN(LTRIM(RTRIM(FIRST_NAME))) = 0
THEN ''
ELSE ', '
END + LTRIM(RTRIM(FIRST_NAME)) AS CHAR(50))
That inline CASE statement qualifies as more than a simple formula or expression, hence the need for the term "snippet."