I am wondering which principle should I use. Here is my situation.
I have a class named TravelOffer. This class looks like this:
public class TravelOffer
{
private final long id;
private final StartZone startZone;
private final EndZone endZone;
private final List<Waypoint> waypoints;
private final Period startOff;
private final User travelCreator;
private final List<User> participantsList;
private final TravelExtras travelExtras;
private final CandidateApprovement candidateApprovement;
private int numberOfSeats;
private double pricePerPerson;
private Luggage luggage;
private boolean additionalLuggageTransport;
private String additionalDescription;
}
As u see there are the following attributes:
User tavelCreator
and List<User> participantsList
What I am wondering is should it be like this or simply to replace the User object with an String userId
and then from a singleton class to get the User object which will be in a Hashmap?
0
I don’t think there’s one right answer because both solutions come with some advantages and disadvantages. I regularly use both depending on the situation.
Having the referenced entity as an object makes this entity class more convenient to use but the downside is that it quickly gets complex to manage all these references. Once the object graph gets more complex you may find yourself in a situation where you can find a chain of references between any two arbitrary entities. Think what happens when you later modify the User
class, for example, and add member List<TravelOffer>
to it. You now have a cyclic dependency and looking up one entity would require you to follow the graph and lookup a whole bunch of other entities you probably will not need. This all can be managed with proxy classes and lazy loading, for example, but that easily gives you new problems to worry about.
Having the referenced entity as an ID is easy for you to implement but makes the entity class less convenient to use. As you mentioned yourself, it would require you to do extra lookups when you use the entity. Using a singleton does not sound like a good idea so this approach would then limit you to making these lookups only in places where you have access to some kind of a repository that knows how to resolve the IDs.
2
It’s probably best to stick with what you have, i.e. as a member variable of type User. Singletons are usually best avoided as they introduce global state. At the moment your class is a bean with no accessors or business logic, if we assume that you’re going to add some business logic at some point then you’ll want to test it, having the user as an (injectable) object will allow you to better unit test your class using stubs or mocks. Also this kind of functionality it typically backed by a database, you’ll be in a better position to model your class graph to a database using ORM such as Hibernate if you maintain the member object. Hope that makes sense?
1