samedi 29 octobre 2016

Why shouldn't services hold state?

Why is it recommended to design services that do not hold any state?

As a visualization, a somehow contrived example would be those two approaches:

1) Here the service maintains its state (often seen as bad practice)

$service->addSubjectForProcessing($subject1);
$service->addSubjectForProcessing($subject2);
$service->addSubjectForProcessing($subject3);
$service->processSubjects();

vs

2) Here the service does not maintain state (generally considered a good practice):

foreach([$subject1, $subject2, $subject3] as $subject) {
    $service->processSubject($subject);
}

Of course there are good pieces of software out there that use both approaches for their tasks, and this is not contested.

However, why is it often advised to avoid state in services?

Aucun commentaire:

Enregistrer un commentaire