Answer the question
In order to leave comments, you need to log in
How to design classes correctly?
Let's say we have an Employee class and Company. I want to implement communication between these two classes. The Employe class will have a company field that will store an instance of the Company class. The Company class would have an employees field, which would be an array of instances of the Employe class.
In js it would be something like this:
function Employe(firstName, company) {
this.firtsName = name;
this.company = company;
}
function Company(name, employes) {
this.name = name;
this.employes = employes;
}
Answer the question
In order to leave comments, you need to log in
This is called a two-way many-to-one connection, and as a rule, you should avoid them if it's completely inconvenient without them. Let's say an employee does not need to know that he belongs to a company. Therefore, we can easily and simply refuse the company property, unless of course we have some specific logic.
class Employe {
constructor(firstName) {
this.firtsName = firstName;
}
}
class Company {
constructor(name, employes){
this.name = name;
this.employes = employes;
}
rename(name) {
this.name = name;
}
addEmploye(employe) {
this.eployes.push(employe);
}
}
How are you planning to use it?
Of course, these classes are only implementation, and Employees and Companies are stored in the database.
So these classes may not be directly related at all, you make a request for some kind of id, to some kind of storage. Even an array can act as a storage, where the keys are id, but the data is already wrapped in a class. In this case, the model class, since it is the model that is responsible for working with the data.
Make the setCompany(Company) method for the employee and use it to register companies with the employee when the list of their employees changes. (one company fires an employee by writing NULL instead of itself in the employee field, and the second one fills in this field)
It is important that there is only one code that supports cyclic references.
A very bad option when both classes have code that rules the same link in the chain.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question