A reader asks:
I have a form and I am generating the dropdowns via a query in a CFC. Is it acceptable to make the functions sort of multi-purpose to generate both the list for the dropdown and single item from the list? I would basically use an if-then statement to add or remove the where clause in the query based on if I needed the full list of query records or just a specific record. To me it seems like a good timesaver from basicly creating identical functions with the only difference being the addition an argument and the where clause in the query but it is very possible that I'm not seeing some obvious or not so obvious pitfalls.
Absolutely! Obviously it will depend on a case by case basis, but in general, yes, it is definitely "ok" to do what you are doing. Many times I will build a generic getAll() method that... well... gets all the data. I will then add a set of optional attributes that act as filters for that method. So for example, I may filter out content that has active=false.
Again - remember that no one answer will cover every situation. Here is an example - you may want to log searches. Your getAll method probably shouldn't be "cluttered" with logging. In that case, I'd maybe build a search method() which does the logging, and then calls getAll, with the appropriate filters. Here is a simple pseudo-code example:
<cffunction name="getAll" returnType="query" output="false">
<cfargument name="searchterms" type="string" required="false">
<cfset var q = "">
<cfquery name="q" datasource="#variables.dsn#">
select name, body
from content
<cfif structKeyExists(arguments,"searchterms") and len(trim(arguments.searchterms))>
where body like <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.searchterms#">
</cfif>
</cfquery>
<cfreturn q>
</cffunction>
<cffunction name="search" returnType="query" output="false">
<cfargument name="searchterms" type="string" required="true">
<cflog file="myapp" text="Searched for #arguments.searchterms#">
<cfreturn getAll(arguments.searchterms)>
</cffunction>