C++/OOP Associations model and database - c++

Edit: I called it association because in my head it should be this, but it seems that I implement it as an aggregation... This can be also discussed...
Context
What you learn in IT is that when you do associations, you should use pointers.
For example: You have 2 objects: Person and Movie. One Person can do several Movie and one Movie can be done by/with several Person. You would then have:
class Person
{
public:
Person::Person();
int id;
vector<Movie*> movies;
};
class Movie
{
public:
Movie::Movie();
int id;
};
main()
{
Person person;
Movie *movie = new Movie;
person.movies.push_back(movie); // With a setter it would be better but...
}
or something like this (please correct me if I do something wrong =D)
Where the troubles appear
Now you have many persons and movies and you want to save it somewhere: in a database.
You get your person
You get all the movies it is associated with in order to construct the whole object.
But how do you get them?
Do you reconstruct a new pointer of Movie for each Person concerned that you associate ?
You lose then the association property that allow the objects to be linked but live their own life.
Do you load all the database in RAM and... ok forget this
What is the way to do it cleverly? What is the proper way given by documentations?
I'm interested in simplified/pseudo code as examples, dissertation... Thx a lot !

Your question is very broad, and there's a number of approaches, how to bind database tables (and represent their foreign key connections).
It's not really only how to represent/handle that kind of Domain Model snippet, you're presenting in your code sample here.
#Martin Fowler provided the EAA pattern catalogue you could reasonably research, and apply appropriate patterns for these kind of object <-> relational mapping problems you address.

Related

I'm using django to build a website and I want to link tutors and students

I'm currently stuck with the best way of assigning tutors to students and then tutors can add lessons for these students and they can both see these lessons, but you can only assign one foreign key to the class "MyLessons". So I'm not sure whether it's worth creating a MyStudents class, storing students inside this (but their user is the same as tutors except is_tutor=false) and then for each student creating a MyLessons class that the tutor can add to.
I think I can make an approach I'm just worried it won't be very efficient or there will be some serious problems later on. Such as the other way was that each lesson would auto take in the tutors email (I set the username to email) and then when displaying the tutors lessons it would go through every lesson and display the lessons with a matching email... problems are though, if I reassign a student to a new tutor I'd like the new tutor to see the lessons but this would mean manually changing each and if there are too many lessons and students the process would get slow.
A Tutor has many students. A student potentially has more than one tutor. So at first glance that's a ManyToMany relational field.
One thing that's at first confusing is that the relationship is symmetric, but is defined on one object and only implicitly on the other. But the implicit and explicit fields both work the same, for manipulating a set of relationships.
class Tutor( models.Model)
students = ManyToManyField( Student, related_name='tutors', ...)
then
student_instance.tutors.add( tutor_instance)
tutor_instance.students.add( student_instance)
both accomplish the same. (In the simplest case. Read the doc for the exceptions).
It may or may not help to know that behind the scenes, Django is manipulating an implicit table whose objects have two fields, a ForeignKey to a student and a ForeignKey to a tutor. It can sometimes be useful to make this table explicit, so you can attach extra information to the relationship such as date created, who created it, etc. Look up the "through" option of ManyToMany if you want to do this.
Further examples here.

What design pattern to use for collection of items?

I am trying to make this example as natural as possible to make it simple.
Lets say I have groups of items. eg item1, item2, item3, item4 etc.
Currently item is represented by struct:
// only contains data
struct item{
string name;
std::vector<string> parts_name;
std::vector<double> parts_price;
std::vector<string> item_color;
...
};
itemx item1, item2...
Then I have class called items
class items{
public:
// return name of all items
vector<string> get_all_item();
// return price of all parts
vector<double> get_all_parts_price();
private:
// hold vector of item
vector<shared_ptr<item>> list_of_items;
// name of item and its parts price
// eg: <item_1_part_1, $1.3>
// eg: <item_1_part_2, $2.3>
// eg: <item_2_part_1, $4.3>
map<string, double> parts_prices;
};
The problem with my current items class is that it is growing really huge,
as feature of item increases.
My solution: make struct item contain function which distributes load
to struct item from class items.
Is there any other better way or any design pattern that is meant for this kind of problem?
It is hard to tell you how to "design" your application based on your input - and I think you are focusing on the wrong aspect here. Your item struct contains vectors. That implies plural. But still, the class is called item.
In that sense: don't think about patterns here. Instead, step back and have a much closer look at the "real world things" you intend to model. You see, the core point of objects and classes is to built a model of the domain you are dealing with.
So a non-answer here: carefully look into the "real-world" relation that your objects have, and then focus on creating a OO model that is helpful to do work flows you intend to implement.

Partialiaze objects in JAVA

Let's say I have a list of Person with some attributes. For each object in this list I want to create a new Person object but only based on some of its attributes.
The Person object has the following attributes : age, name, disease.
I want to create a new Person only on its age and name. The disease attribute must be confidential.
How could I do that ?
Thanks in advance !
You very easily could do this by creating a new object entirely which does not hold that information. For example, you could make a class such as this
public class PersonNoDisease {
private int age;
private String name;
...
}
If you want to make sure that PersonNoDisease still has many of the same methods that the original person class did, you should create an interface that they both implement to ensure that they both have the methods which you think they should both have. If you don't have getters in the Person class, you should make those so that it will be easier to initialize this new class.

Is it mandatory to specify intermediate model to describe 'level' of many-to-many relationship?

Being new to Django and relatively new to python, I am writing a knowledge reporting webpage.
I have 2 models with a defined MtM relationship:
Class Student:
level_of_knowledge = model.ManyToMany(Topic)
...
Class Topic:
...
Intended usage:
Every Student has a level of understanding of every topic (the list of topics is exactly the same for everyone), starting with, say, "Basic". The level of understanding may be increased to "Intermediate" and further to "Advanced".
Question:
Is it necessary to implement an intermediate "through" model with the determined list of levels of undestanding, or can it be done in the level_of_knowledge field in Student model directly?
Personally, I would create an intermediate model in this case, but if you want more ideas of what you could do then something like this would work too:
Class Student:
advanced_knowledge = model.ManyToMany(Topic)
intermediate_knowledge = model.ManyToMany(Topic)
basic_knowledge = model.ManyToMany(Topic)
...
Class Topic:
...
So this is neat because you can easily access knowledge of a certain level by using student.basic_knowledge.all()
But here's the problem:
What if you want a list of all Topic objects related to a Student? Do you combine all three of these queries?
What if you want to add a few more knowledge levels? Maybe later students will have beginner knowledge or expert knowledge. How many other ManyToMany fields will you end up adding?
Using an intermediate model solves both of these problems, and its not hard to use the django through option and filter by levels if you want. Just make properties or methods on Student for the knowledge levels you filter by most often.
Class Student:
level_of_knowledge = model.ManyToMany(Topic, through=MyIntermediteModel)
def advanced_knowledge(self):
return self.level_of_knowledge.filter(...) # filter by intermedite model where level = 'advanced'

C++ : Generic interface design for Database

I have a class which is used to create connection with database:
class DBHandler
{
public:
DBHandler();
~DBHandler();
int connect();
int execQuery( string query);
string getField( int row, int col);
};
Now there is another class which is used to fetch some info from database,
class DBManager
{
public:
DBManager();
~DBManager();
//Approach 1
string getUsername()
{
//create a query here and use object of DBHandler class to execute it.
}
//Approach 2
string getUsername (struct QueryDetails& qDetails)
{
//create query using fields of structure and execute the query using DBHandler class.
}
};
Now here is the problem:
1 ) which approach should I follow:
A) If I use approach 1, then I need to hard code query.
B) If I use approach 2, then I need to fill structure each time before calling to function getUsername.
2 ) Is there any better solution except these two which would be generic ?
PS : Definition of structure
struct QueryDetails
{
string tableName;
vector<string> colList;
...
};
Your question is very broad, and the elements you give do not permit to propose you an objective best answer.
Your approach 1 has the following advantages:
it is a robust and secure approach : The queries are written with knowledge of the relevant object
if the database evolve it's easy to find out (text search) where specific queries are made for the tables, and updated the querying code for your object
if your object evolves, needless to say, that you'll immediately realise what you have to change on the database side
The main inconvenience, is that you're tightly linked to the database. If tomorrow you change from PostGres to something else, you have to rewrite every query.
Your approach 2 has the following advantages:
It is very flexible
If your database change, you have to change only the generic functions.
The inconvenience is that this flexibility bears a lot of risks for the maintenance: you can't be sure that the correct query is send by the client, and impact assessment of database layout changes are very difficult to assess.
So finally, it's up to you to decide which one would more fit your needs.
I'd personally tend to favour 1. But this is subjective, and I'd anyway introduce an additional layer to make the application code more independent of the database system that implements access to database.
However, depending on your need, a greater flexibility could be of advantage. For instance, if your class is in fact meant to be a middle layer for other calsses to fetch their own data, then approach 2 could be the best option.