Home > OS >  Understanding how to model UML Class/Database
Understanding how to model UML Class/Database

Time:02-20

I'm confused with designing a client software with database integration to what should be a member variable of the class or just a query to the database. Let me be specific with a trivial example:

If I have, lets say, a Student class, which has a list of "friends" that are Student objects. Should my software design have an ArrayList<Student> as a member variable of the Student class or should the Database deal with the relationship itself and the Student class doesn't account for those "friends"? How should a proper UML be in this case?

CodePudding user response:

You need a one-to-many relationship between Student and friends in both the relational database and the object model.

CodePudding user response:

This question is broader than you may think, as there are many ways to deal with it. Here some first ideas:

In principle, you could very well load from the database a Student object. You'd create it based on data in a row in a STUDENTS table. Since the friendship between students is a many-to-many association, you'd have to read an association table, say STUDENT_FRIENDS, relevant pairs of ids of befriended students.

But how to use these tables in the application?

  • A first possibility would be to load each Student friend and insert it in the ArrayList<Student>. But each loaded student is like the first student and could have oneself friends that you'd have to load as well! You'd end up loading a lots of students, if not all, just for getting the single one you're interested in.
  • A second possibility would be use an ArrayList<StudentId> instead of an ArrayList<Student> and populate it. You'd then load the friends just in time, only when needed. But this would require some more important changes in your application.
  • A third possibility is not to expose an ArrayList. Not leaking the internals is always a good idea. Instead use a getter. So you'd load the friends only if student.getFriends() is called. This is a convenient approach, as you'd have a collection of friends at your disposal, but avoid being caught in a recursive loading of friends of friends.

In all the cases, you may be interested in using a repository object to get individual or collections of students, and encapsulate the database handling.

Advice: as said, there are many more options, the repository is one approach but there are also active records, table gateways and other approaches. To get a full overview, you may be interested in Martin Fowler's book Patterns of Enterprise Application Architecture.

  • Related