Create separate java bean for an ArrayList property

476 views Asked by At

I have two types of java beans that can be associated with a User java bean: PrivateTeacher and CompanyTeacher. These two java beans are similar, only for one of their properties, say "subject", the PrivateTeacher will always have one while the CompanyTeacher can have several. Would it make more sense to have a single java bean for both of these types of users where the "subject" field will be an ArrayList and the PrivateTeacher will only fill one element of the ArrayList whereas the CompanyTeacher can fill several?

Or should I have two separate java beans: one with an int field and another with an ArrayList<Integer> field (for the subject id's field)?

On one hand, the latter way is more precise. On the other, I don't want to limit methods that I have such as say, "findTeachers", which could satisfy both types of java beans (pass a parameter saying the bean type: "company" or "private" and then the User bean will be different but the Teacher bean will be the same). Any suggestions or explanations? Thank you

2

There are 2 answers

0
Arek On

It depends...

If you want to treat both PrivateTeacher and CompanyTeacher in the same manner (polymorphicaly) then List<Integer> (not ArrayList) would be a better approach. But if this is not the case then - use the more precise way to describe them.

0
Sharon Ben Asher On

You can have a PrivateTeacher that supports both methods:

public String getSubject(int index) {
  return index < subjects.size() ? subjects.get(index) : subjects.get(subjects.size()-1);
}
public String getSubject() {
  return getSubject(0);
}