You need to add some new functionality to your function or class. Let’s say you need to remove all objects stored, but optionally also call a method on them.
It’s pretty simple, isn’t it? Let’s just add a parameter to removeAllObjects! If you make it true, the additional method is called, otherwise not.
Except it’s not really such a good idea at all…
What’s wrong with parameters?
Is there something wrong with parameters?
No, not really.
Parameters are good, but there are some things that you need to consider when creating functions with parameters, or when adding parameters to existing ones. Let’s look at them in a bit, but first let’s do a quick comparison.
Here’s some code:
$pump = new OilPump(); $pump->turnSwitchOff(true);
Compare it to this:
$pump = new OilPump(); $pump->turnSwitchOff(); $pump->deactivate();
Did you know what the parameter for
turnSwitchOff did in the first snippet? Unless you’re really good at guessing, you probably had no clue.
This illustrates the case against parameters quite well: In many cases, some parameters are not obvious at all, and to know what the parameter does, you would have to look it up in your docs or source.
Rules for good parameters
The first rule is easy: Less parameters is good. However, this does not mean you should avoid parameters like plague – while less is good, not having enough and instead having more functions is often worse.
The second rule is that your parameters should be related to the function. In our first example and the code sample, the parameters we talked about weren’t related to the functions at all. If the parameter is related, and easily understandable from the function name, it’s probably OK. For example:
Pretty self-explanatory, right?
The fourth rule is use the language you program in to your advantage. In Python, you can use “kwargs” like this:
<Your rule goes here. Write it in the comments!>
Putting in parameters for functions/methods without thinking much is an easy way to end up with a lot of confusing code. It’s a good rule to think if it’s possible to guess the parameter’s meaning from the method’s name or other clues. When in doubt, adding the new functionality with a new method is usually a safe route – but don’t forget that sometimes you can’t have everything.
Sometimes you need to have a bunch of parameters. In situations like these, it’s important that you have good docblocks (PHPDoc, JSDoc, some other flavor) and good parameter naming – while less parameters is often good, it’s easy to go too far.