- January 26, 2024
- Posted by: Bharat Patel
- Category: ColdFusion
Is it mandatory to set cfargument when writing a function?
Yes
, but the correct response is No
.<cfscript>
function printMe() {
return arguments?.name;
}
dump(printMe())
dump(printMe(name = 'Bharat Patel'))
</cfscript>
If an argument isn’t required to be set, why does it exist, and why does it have various attributes? What is the purpose of this tag? Quite a few questions, aren’t there? Please allow me to explain everything about it; afterwards, any lingering doubts might be dispelled.
First and foremost, it provides clear documentation of the function so that it is advisable to set. In the below example, the argument
gives you clear instructions what name
is required, and it accepts only string. Isn’t it helpful?
<cfscript>
function printMe(
required string name
) output="true" {
writeOutput("<h1>#name#</h1>")
return;
}
</cfscript>
Should we mix up required
and default
attributes together? My stance is no. If we set required
to true
, we expect a value from the user. Conversely, if we set required
it to false, it becomes an optional parameter, and I don’t see the need to set an default
attribute. Do you agree, or do you have a different opinion? Note that when we set required
to false
then we have to check the argument
exists or not before utilizing the value of the argument.
What is the purpose of the ‘default’ attribute, though? If we set default attributes, the Rapid Development Language (ColdFusion/Lucee) automatically understands that if it doesn’t receive a value, it should consider the default one.
Lastly, I’ve observed in many CFML projects that the type
attribute is often missing. The type
attribute has its own power to validate incoming values and also provides documentation for the argument, as I explained earlier.
In conclusion of this article, I would suggest that we should write cfargument with proper attributes, even though CFML technology allows it without them.
<cfscript>
function sendMail(
required string fromAddress,
required string toAddresses,
required string subject,
required string content,
numeric priority = 1, // urgent
string ccAddresses,
string bccAddresses,
array attachments
) output="true" {
dump(arguments)
}
sendMail(
fromAddress = "test@example.com",
toAddresses = "one@example.com,two@example.com",
subject = "test email",
content = "body of the email",
attachments = [],
priority = 2
);
</cfscript>
Happy Coding!