Reputation: 11132
Say I have a class Person
, which has a method doSomething()
. I create a static ArrayList<Person> people
, and a method doSomethingToAllPeople()
which calls doSomething()
for each Person
in people
. Should I put people
and doSomethingToAllPeople()
in the Person
class or in a different PersonManager
class? Does it even matter? Here is some example code:
class Person
{
public void doSomething()
{
//stuff here
}
}
//where should the following code go?
static List<Person> people = new ArrayList<Person>();
for(int i = 0; i < 10; i++)
{
people.add(new Person());
}
static void doSomethingToAllPeople()
{
for(Person person : people)
{
person.doSomething();
}
}
Upvotes: 0
Views: 105
Reputation: 941
In short, it doesn't matter and is a matter of preference. However, if you want my opinion, I would consider keeping your Person
class independent of your collection of Person
s. Keeping these two parts separate preserves flexibility of the class, and one of the great things about Java is that it enables you to create nice, contained, reusable classes.
Consider a PersonRegistry
class that implements a factory design pattern. It might have a method that creates an instance of Person
and adds this instance to a collection before returning. This will enable to achieve your desired functionality while keeping Person
independent and flexible.
Upvotes: 1