Over the last few months I have been working with Symfony and have got used to passing values to methods via an options array but I have recently had to pick up an older project in which the values are passed to the methods by individual parameters.
This has given me a good opportunity to evaluate both techniques and determine my personal preference for working.
The more traditional technique is to pass values to methods using individual parameters as in the example below:-
public function someMethod($name, $age = null) { // do something }
The benefit I have found with this method is that you can clearly identify what needs to be passed to the method, however, if you need to change the method to include an additional parameter it means that you have to update every call to this method so that every parameter is specified.
An alternative (and my personal preference) is to used an option array like in the following example
public function someMethod($options = array()) { $defaults = array('name' => 'chris', 'age' => 18); $options = $options + $defaults; $name = $options['name']; // do something }
In this case, if you need to add an extra parameter to the method you can simply add the value to the options array and update the functionality within the method. You do not necessarily need to update the calls to this method that are already in place because they should still work fine provided the updated functionality is defined in such a way that it allows for the new parameter to be optional.
In addition, I feel that if you provide decent documentation regarding the options array (which should include a list of all the options values allowed), especially if it can be picked up via auto-completion in IDEs such as Netbeans, then this is just as easy to use as methods which are defined to accept individual parameters.
Comments
Leave a comment Trackback