What is the best approach for using a foreign key member in a class? Composition of the whole object or simply declare a variable


Lets suppose I have a class Student and a class ExamRecord. Now ExamRecord uses Student.ID as foreign key in the DB. How should I cater it in the Front-end model? Should I use composition and make an object of type Student as member of ExamRecord (so I can use its ID later on when needed to be) or just declare a simple int (assume int is the datatype of the ID) and use it for storing Student ID in the ExamRecord?

I'd go with storing it as an int in the class. I'll try to explain why.

When working with databases you're trying to model relationships between entities, like in your case you have an ExamRecord which has a foreign key to a Student. Now this might seem like it could be (and surely it can) be translated directly to program code. But there's a semantic difference here that I think is fairly important.

That is, as mentioned, when working with relational databases you model relationships and in your code you're trying to model objects with the help of classes. These objects do have different relationships with other objects, otherwise it would be very hard to code and in OOP the relationships is one of its strengths. However you've surely heard about Is a (inheritance/interfaces) and Has a(composition) which is the common way of talking about OOP-relationships. Does the exam record have a student?

I guess what I'm trying to say with my ramblings above is that the models in a database are different from the models in a program.

What it boils down to is semantics, what makes sense and what conveys the meaning of your code the best? I said that I'd go with the ExamRecord storing the student-id because to me it sounds strange that an ExamRecord has a Student, the other way around though makes perfect sense. But again, it's about what makes sense in the context of your program and only you can answer that.