Java - Best way to return multiple object types from a method

containment, inheritance, java

Solution

You can either handle this through inheritance, or containment.

You can have `Person` and `DataExporterPerson` extend something like `AbstractPerson`. However, since you have not already done so, then it is probably inappropriate to do inheritance.

I think it was Effective C++ that talked about how containment is better than inheritance. IIRC the reason stated is that containment is more loosely coupled than inheritance.

Here you would have a object that contains both `Person` and `DataExporterPerson`. Your method would populate one of those for this union type object, and by seeing which one is null you would know which one you actually have.

public class DBPersonUnion {
  private Person person = null;
  private DataExporterPerson dataExporterPerson = null;

  //getters and setters.
}

Problem

In my DAO i have a method where i build 2 different objects and I want to return both of those objects, but i'm not sure what the best way is to do it. I've looked at using `? extends myObject`, creating another class that holds both of my objects that i want to return, and just using `List<Object>`. Long story short on why i need these similar objects is to display 1 on the screen and the other to use with primefaces dataexporter which doesn't handle lists in an object as far as i'm aware. Class Person ``` public class Person() { firstName = null; lastName = null; List<Programs> programs = new ArrayList<Programs>(); // Getters and setters } ``` Class DataExporterPerson ``` public class DataExporterPerson() { firstName = null; lastName = null; String program = null; // Getters and setters } ``` DAO method: ``` public List<SOMETHING> getPeople() { // query db for people // build both objects return ????? } ``` Now i understand i can very easily create another object like the one below, but that seems like an inefficient way to do things because i'm basically creating an object just to return from 1 method. ``` public class PersonTransporter() { Person person = null; DataExporterPerson = null; } ``` What is the best way to handle this scenario? EDIT The reason that i'm trying to return 2 objects in 1 method is because this is a DAO method that queries the database and builds 2 objects based on the data in the query. I don't want to break it up into 2 methods because i don't want to query the db twice if i don't need to.

Original source

Related problems