F
F
Fedor2016-04-04 18:08:02
JavaScript
Fedor, 2016-04-04 18:08:02

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;
}

Is this design approach correct? If so, then the next question is: what is the best way to implement methods that would control the state of these two classes? If, for example, the company field of an instance of the Employe class changes, then the fields of the two corresponding instances of the Company class must also change fields. How it is better to implement it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2016-04-04
@whyamiscott

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);
    }
}

A
Alexander Litvinenko, 2016-04-04
@edli007

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.

A
Andrey, 2016-04-04
@AndryG

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 question

Ask a Question

731 491 924 answers to any question