Search code examples
design-patternsclass-design

Best approach for OOP Class relationship design


I have got a designing dilema. I have a class named UserAccount that represent a user that has the ability to log into a school system and access information like the courses he/she is taking, avatar, news, etc. Then there is another class named Course that represents any course given in this school. It holds information like the amount of students that are taking this course in this term, the course id number, etc.

So the UserAccount has a method like this

UserAccount user = new UserAccount("username", "password");
user.login();
Array<Courses> courses = user.getCourses();

This method getCourses() will return an array of courses with the courses the user is taking. So is obvious that the object user holds a reference to the courses he/she is taking.

But, and here is my problem, the course has to access information from the server(using REST) but all the requests have to be sent with the session cookie and some user's info. So somehow the course has to know which user is trying to get the info. For me it seems wrong that the course holds a reference to a user and having to pass the user as a parameter to course's method that needs this info seems to be wrong too.

Does anyone have a better solution?

NOTE: I have no control on how the system was designed, I should have told that actually there is no public API, I'm scrapping the html responses so I don't know how the system was implemented and I don't need to check which courses is the student taking, that information is given by server by doing a simple request. As I said before the problem is that when I have to make the request to the server (regarding to courses info) I have to send the session cookie and some other not public information that is being hold by the user object because the user must be logged in to get the information from the system. The thing is that it doesn't feel natural that the course should have a reference to the student.


Solution

  • Course shouldn't do requests if it doesn't have data. Solutions I see are :

    • Another object could collect data from User and Course and do the request.
    • Do not return Courses from User but UserCourse or something related to user that would have a reference to the user and the course.
    • Pass a user as a parameter to the method that do requests requiring user data.
    • Eventually realize that Course might be related to the User and give a reference to User to Course ?