Ok, in my database I have a table Event and a table Room. Each Room can have many Event.
Room table roomID-roomName 1 - cafe102 ... Event table eventID- Time -type -roomID 1 - 11:20 - 1 - 1 2 - 15:20 - 1 - 1 ...
So I want to crate a Class structure that mimics the DB structure.
public class Event{
private int eventID;
private String time;
private int roomID; // or
private Room room;
public Event(){
}
/// all set and get methods here
}
public class Room{
private int roomID;
private String roomName;
public Room(){
}
//all Set and Get methods here
}
My question is, in the Event
class, should I have type private int roomID;
or private Room room;
?
Also is there any reason to put private Event event;
into Room
class? Or does it just depend on the need and there is no standard?
1
ID is a way for the database to connect a room to an event, there’s no need to duplicate that in the class. So I’d definitely choose private Room room;
. This will create a much better object model than having a bunch of IDs.
As to your other question, I’d say it depends on your needs whether you need a two-way reference or not. From modeling point of view it seems more natural that an event has a room assigned and the room doesn’t need to know the events. But if you need to show the booking status of a particular room or something like that, then adding the reference might be a good idea.
However, you should notice that it’s a one-to-many relationship, so one room can have more than one event. So if you want the Room
class to know the related events, your variable needs to be private List<Event> events;
(of course it can also be some other structure than a list).
1
I do not understand why you would need to have the roomID on the Event on the code itself (you use this relationship just for the DB). I would rather say that you can point directly to the Room Object. (private Room room );
Now, the second question why would you put an Event attribute to a Room? I would say that you can create in your application a list of Events which have the same room, but I do not understand why you would say that a Room have events. Maybe the concept of the room is the list of events it contains?
I hope this helps.
If you need a reference to an Event
in your Room
class I see no reason why you shouldn’t. In ORM’s such as EntityFramework in .NET, ActiveRecord in Ruby, this is allowed, so I guess it is OK to do it.