czwartek, 14 stycznia 2010

Pai Mei's First Lesson: How many method parameters is too many?

Welcome to Pai Mei's programming tutorial ;)

Lesson One: How many method parameters is too many?

Many times I see people struggling with maintaining their code because they have too many method parameters. They have lots of methods that take the same list of e.g. 8 parameters, and when it comes to adding another one, they have hundreds of places to change.

If your method has up to 3 parameters, it's probably ok.
If your method has between 4 and 6 parameters, consider creating a class which holds parameters that have something in common (thus limiting number of parameters).
If your method has more than 6 parameters, you have to find a way to limit their number. Creating a parameter object (as mentioned above) is the best way to achieve it.

Sticking to these rules will help you design better methods. They will be much easier to maintain.

And one more silver bullet. If you see methods that share common list of parameters, and what is more, all parameters create one logical object, consider creating a class that implements these methods. Remove the parameters by replacing them with class properties.

These two techniques are very easy to implement and dramatically improve your code design.

Since your arm now belongs to me, I want it strong. Can you do that?

Brak komentarzy:

Prześlij komentarz