Answer the question
In order to leave comments, you need to log in
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
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;
}
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 questionAsk a Question
731 491 924 answers to any question