E
E
Evgeniy Rybalko2020-06-29 14:06:52
Java
Evgeniy Rybalko, 2020-06-29 14:06:52

Is it possible to create new entities in getters?

Good afternoon.
Everywhere I read many times that each method should do one action
. For example, a getter - only to get the field value.

But I ran into such a task
. I have a service that receives the current state of an object, for example, I would like it to the state was not defined for this chatId, then it was created Is this the right approach? For this, the hands of the seigneurs are torn off?
public State getState(Long chatId)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry, 2020-06-29
@whereeaglesdare

I would not do this, because if the state is not found for the chatId, then it is definitely not the responsibility of the class to create this state. The class only returns the state if it exists, and now it turns out. that the class is also responsible for creating this state. And if the state object is complex, then the whole factory will have to be transferred to the entity, which at least violates the single responsibility principle.
In this case, it's better to return null and check for null. Or do the right thing and create a function:

public boolean checkState(Long chatId)
{
    return false;
}

and based on the presence of the state, either return it or create it.

D
Dmitry Roo, 2020-06-29
@xez

Better to do two methods:
get
And
getOrCreate

A
Alexey Tsarapkin, 2020-06-29
@Dreamka

Purely technically, nothing prevents you from doing this, but to create a new entity, I would personally use a different method. If the entity in the geter cannot be obtained, return false, for example, and check the receipt of the type

if ($model->getState()) {

} else {

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question