SOLID: The Single-Responsibility Principle (SRP)
This Object Oriented Programming principle states that each module or class should be responsible for only one part of the functionality.
By saying this, we are stating that each subsystem, module, class or function should have just one reason to change.
How do we accomplish this? By developing small service classes with enclosed objectives.
- More cohesion and less resistance to change.
- Allow the composition of classes (or class injection) which deserves a extended post in this blog.
- Avoid duplicity and copy-pasting portions of code.
"Gather together those things that change for the same reason, and separate those things that change for different reasons."
So, as you can see, we are talking all the time about the same criteria to decide whether or not applying this principle to our code and where: predicting change. Again, the app we design for our cousin (aka, the jeweler of the family) is not likely to need a bunch of changes, other than adding new business lines, like, for example, adding jewels for men, or a specific jewels collection for babies. On the other hand, in the case of the app created for the newly implemented Logistics department for a flourishing company, changes are more than likely to happen within a short period of time.
And before finishing, I'll leave in here part of my own code that I think could be refactored using this principle:
public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder )
{
try {
if ($this->isUserAlreadyLoggedIn()) {
$this->throwAlreadyLoggedInUserMessage();
return $this->redirectToRoute('profile');
}
$this->generateForm($request);
if ($this->form->isSubmitted() && $this->form->isValid()) {
$this->createNewUserEntityService($passwordEncoder);
$this->createNewGameSessionService();
$this->createNewGameHistoryEntryService();
$this->createSuccessfullyRegisteredNewUser();
return $this->redirectToRoute('app_login');
}
return $this->render('registation/index.html.twig', [
'form' => $this->form->createView(),
]);
} catch (\Exception $exception) {
$this->createErrorMessage($exception);
return $this->render('registation/index.html.twig', [
'form' => $this->form->createView(),
]);
}
}
- Create a new User
- Create a New Game Session
- Create a New History Entry
Comments
Post a Comment