BC Tech : Free Tutorials and More Advertisement
Main arrow News / Articles arrow Pass structures to functions rather than separate arguments
Wednesday, 07 January 2009
 
 
Pass structures to functions rather than separate arguments Print E-mail
Tutorials / FAQs - Programming
Article Index
Pass structures to functions rather than separate arguments
Page 2

My post got longer and longer as my thoughts came together on this subject. The gist of my claim is that you shouldn't build something as FRAGILE as a function that breaks if there are argument variations, when you can simply build a more robust function in the first place. The final answer? Pass in a structure rather than require ongoing maintenance of all references to a function so as to avoid an error you never should have gotten in the first place.

An unchanging set of arguments makes sense when you're working with a small codebase, but sometimes one might want to call a function from multiple locations that have different requirements. Suppose you have a PHP function that creates and executes a MySQL select query. A search page might be designed to support text matches on a couple columns, only to find out that additional fields need to be supported for generating reports.

There are two options here. You can create your function with a static set of arguments that fails when it is called with missing parameters, then counter with the retort that the dude who called it was a "bad programmer." This is totally useless when your production sites are throwing unnecessary errors. The second option is to pass in a structure and simply check for various optional arguments.

When I need to expand the capabilities of an existing function to support new requirements, I simply have to make a modification to the UDF rather than to all existing code. You might disagree with me, but I can guarantee it's a lot easier to maintain a site when you don't have to touch all references to a function whenever you want to improve it.

Any "professional" programmer who relies on the vast repository of *documentation* present in most projects in industry is either an idealistic novice, or EXTREMELY fortunate for the places they've worked.



 
Next >
Google
 
Web benconley.net
 
Top! Top!