0

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();
    }
}
4
  • 3
    Use static placeholders as little as possible. I'd recommend you create a PersonRepository class with an instance member List<Person>. Create an instance of PersonRepository and have it manage your Persons Commented Dec 15, 2013 at 19:35
  • You'd acheive the same functionallity. It's basically a matter of taste, and a matter of if you want anyone using Person to be exposed to people. Commented Dec 15, 2013 at 19:35
  • I agree with @Sotirios, but if it's just one place where you need to manage something for a bunch of people (e.g. List<Person>), I'd just pass the List<Person> as an argument to the static method doSomethingToAllPeople(). Commented Dec 15, 2013 at 19:40
  • Just think of static as something that will last for entire application lifetime. variable or class is usually declared static if you want only one instance during entire lifetime. Commented Dec 15, 2013 at 19:40

1 Answer 1

1

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 Persons. 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.