Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Object Calisthenics: 9 regras que vão mudar sua forma de programar 🇧🇷

Object Calisthenics: 9 regras que vão mudar sua forma de programar 🇧🇷

Escrever bom software é difícil, não se iluda, e geralmente passamos mais tempo lendo código que escrevendo código. Para escrever bons códigos você precisa ler bons códigos, isso é um hábito, e vem com o tempo, não adianta correr. Uma boa dica para melhorar sua escrita é utilizar de Object Calisthenics, que são 9 regras para "enxugar" suas classes, tornando-as muito mais fáceis de serem entendidas. A partir daí, é só correr pro abraço!

Junior Grossi

May 18, 2019
Tweet

More Decks by Junior Grossi

Other Decks in Programming

Transcript

  1. SOBRE SOLID: É um objetivo muito ousado Exige muitos conceitos

    de OOP Envolve muita experiência em abstração Exige um time muito "Maduro "
  2. ATENÇÃO Não se engane Algumas regras são bem difíceis Aplique

    com cautela Não seja um extremista Invista tempo em cada regra Algumas regras são dependentes
  3. public function notify(DateInterval $dateInterval): void { $posts = $this­>postsRepository ­>findByDateInterval($dateInterval);

    foreach ($posts as $post) { $totals = $this­>report­>calculateTotals($post); foreach ($post­>authors() as $author) { $this­>message­>sendTo($author, $totals); } } } 1 2 3 4 5 6 7 8 9 10 11 12
  4. $totals = $this­>report­>calculateTotals($post); foreach ($post­>authors() as $author) { $this­>message­>sendTo($author, $totals);

    } public function notify(DateInterval $dateInterval): void 1 { 2 $posts = $this­>postsRepository 3 ­>findByDateInterval($dateInterval); 4 5 foreach ($posts as $post) { 6 7 8 9 10 } 11 } 12
  5. $this­>notifyAuthors($post); private function notifyAuthors(Post $post): void { $totals = $this­>report

    ­>calculateTotals($post); foreach ($post­>authors() as $author) { $this­>message ­>sendTo($author, $totals); } } public function notify(DateInterval $dateInterval): void 1 { 2 $posts = $this­>postsRepository 3 ­>findByDateInterval($dateInterval); 4 5 foreach ($posts as $post) { 6 7 } 8 } 9 10 11 12 13 14 15 16 17 18 19 20
  6. MOTIVOS Porque else não serve para nada Porque você não

    precisa do else Na verdade você nunca precisou do else
  7. private function authorizeUser(User $user): bool { if ($user­>isAdmin()) { $result

    = true; } else { $result = false; } return $result; } private function authorizeUser(User $user): bool { if ($user­>isAdmin()) { return true; } return false; // Ou só return $user­>isAdmin() }
  8. private function response(Request $request): Response { if ($request­>expectsJson()) { $response

    = $this­>createJsonResponse(); } else { $response = $this­>createHtmlResponse(); } return $this­>formatResponse($response); }
  9. private function response(Request $request): Response { $response = $this­>buildFromRequest($request); return

    $this­>formatResponse($response); } private function buildFromRequest(Request $request): Response { if ($request­>expectsJson()) { return $this­>createJsonResponse(); } return $this­>createHtmlResponse(); }
  10. public function charge(int $amount, string $currency): string { $this­>paymentProvider­>chargeUser( $this­>user­>id(),

    $amount, $currency ); return $this­>paymentProvider ­>confirmationNumber(); }
  11. class Money { private int $amount; private Currency $currency; public

    function __construct(int $amount, string $currency) { $this­>amount = $amount; $this­>currency = new Currency($currency); } public function amount(): int { return $this­>amount; } public function currencyAbbreviation(): string { return $this­>currency ­>abbreviation(); } }
  12. class Currency { private string $abbreviation; public function __construct(string $abbreviation)

    { if (!$this­>abbreviationIsValid($abbreviation)) { throw new InvalidCurrencyAbbreviationException; } $this­>abbreviation = strtoupper($abbreviation); } public function abbreviation(): string { return $this­>abbreviation; } // Code }
  13. CONCEITO Manipular objectos similares em um só lugar Somente uma

    propriedade por classe collection Métodos realizam ações no conjunto de objectos
  14. class ActiveUsersCollection implement Iterator { private array $users = [];

    public function __construct(array $users) { $this­>users = $users; } public function filterByActivationProcess(): self { // Code } }
  15. class RemoteCompany { private CountriesCollection $countries; public function addCountries(EmployeesCollection $employees):

    void { foreach ($employees as $employee) { $this­>countries­>add( $employee­>address­>country­>code(); ) } } } 1 2 3 4 5 6 7 8 9 10 11 12 13
  16. class RemoteCompany { private CountriesCollection $countries; public function addCountries(EmployeesCollection $employees):

    void { foreach ($employees as $employee) { $employee­>addToCollection( $this­>countries ); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13
  17. DICA MAROTA TRILEGAL Nomes estão ficando muito grandes? Reveja SRP!

    Sua classe/método pode estar fazendo coisa demais
  18. class Customer { private Name $name; private int $customerId; }

    class Name { private string $firstName; private string $lastName; }
  19. MOTIVOS Podem ferir SRP / Encapsulamento Regra: Tell, don't ask!

    Não possuem significado algum "Immutable classes" pra accessors (sem tomada de decisão)
  20. Você escreve para outro dev ler Você pode ser esse

    outro dev Devs são burros preguiçosos Incluindo eu e você Previna problemas com devs