Clean Code by Robert C. Martin suggests that you have as few parameters as possible with three being the general ceiling, and four as an extreme, possibly indicating you need to refactor.
How many parameters is too many is subjective. I personally think the above is a tad extreme and use up to three or four, sometimes five, in functions/methods but I have some constructors that require more.
What I find is, when you work with a larger application, your classes require a handful of parameters in addition to what I will call core/application classes. I pretty much avoid globals and static functions altogether and inject everything but in the higher level classes I sometime end up with three or four injections in the class that are quite specific in addition to a handful of other objects (up to six or seven) for things like:
- Logging
- Database abstraction
- Event manager
- Errors
- Utility classes for date, strings, JSON, scalar, etc
- Config
These tend to be either wrapper classes for core PHP functionality ā which would be globally available anyway ā or they need to be available anyway in the application ā such as logging and broadcasting and listening to events. So, I think they are legitimate dependencies and not a sign the classes are doing too much.
As far as I can see there are several options that donāt require using global variables or having classes create their own objects:
- Store all the core objects in a registry and inject that
- Aggregate the core objects into groups and inject them as they are needed (I could probably group all these into: Database, Files, Utilities and Application)
- Inject all objects individually and accept the fact that some higher level classes will have 8ā12 injections in the constructor
- Use a builder pattern and build up the objects piece by piece
Option 1 to me is only a step up from globals. I personally hate option four, which leaves me with 2 or 3.
What are your thoughts? What would you do?