Reputation: 2497
Let's say that class PersonList
has the method AddNewPerson()
, which creates and adds a new Person
to an internal list. However, the constructor of Person
requires several parameters (mostly interfaces it depends on). This means that PersonList
will also require to have those parameters passed to its constructor (or somehow made available).
This arrangement seems like a code smell because PersonList
doesn't use any of those dependencies directly. It simply passes them along to another's constructor. How may I refactor these classes so that it's clear what the real dependencies are for each class?
Upvotes: 0
Views: 34
Reputation: 43718
"This means that PersonList will also require to have those parameters passed to its constructor (or somehow made available)."
Why would that be? PersonList
doesn't have to be a factory for Person
objects, you can pass Person
s directly to AddNewPerson
instead.
E.g.
public void AddNewPerson(Person person);
However, if you both wishes to relieve the client code from creating Person
instances and at the same time you want to avoid having PersonList
to depend on what's needed to create Person
s then you may introduce a PersonFactory
that would encapsulate the creation logic as well as the dependencies needed.
In that case the client can either use the PersonFactory
to create Person
s and add them to the list or the PersonList
can depend on the PersonFactory
.
Upvotes: 1