Top Banner
Hexagonal Architecture Gabriele Tondi - @racingDeveloper
61

XPug Milano - Hexagonal architecture

Feb 21, 2017

Download

Technology

Gabriele Tondi
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: XPug Milano - Hexagonal architecture

Hexagonal Architecture

Gabriele Tondi - @racingDeveloper

Page 2: XPug Milano - Hexagonal architecture

Metwitter: @racingDeveloper mail: [email protected] work: agile software developer @ love: metodologie agili (XP), OOD, TDD… and races

Page 3: XPug Milano - Hexagonal architecture
Page 4: XPug Milano - Hexagonal architecture

Cos’è un’architettura?

Page 5: XPug Milano - Hexagonal architecture

Il web é un’architettura?

Page 6: XPug Milano - Hexagonal architecture

Perché è importante l’architettura?

Page 7: XPug Milano - Hexagonal architecture

due valori del software

Page 8: XPug Milano - Hexagonal architecture

Valore Secondario rispetta gli attuali requisiti

Page 9: XPug Milano - Hexagonal architecture

Valore Primario tollerare e facilitare i requisiti futuri

Page 10: XPug Milano - Hexagonal architecture
Page 11: XPug Milano - Hexagonal architecture

MVC è un’architettura?

Page 12: XPug Milano - Hexagonal architecture
Page 13: XPug Milano - Hexagonal architecture

Cosa fa questa applicazione?

Page 14: XPug Milano - Hexagonal architecture
Page 15: XPug Milano - Hexagonal architecture

Aiutino

Page 16: XPug Milano - Hexagonal architecture
Page 17: XPug Milano - Hexagonal architecture

Cosa fa questa applicazione?

Page 18: XPug Milano - Hexagonal architecture
Page 19: XPug Milano - Hexagonal architecture

VISITORS?

Page 20: XPug Milano - Hexagonal architecture

CONTACTS?

Page 21: XPug Milano - Hexagonal architecture
Page 22: XPug Milano - Hexagonal architecture

Cos’è?

Page 23: XPug Milano - Hexagonal architecture

CHIESAAAAA!

Page 24: XPug Milano - Hexagonal architecture

L’architettura ci deve dire COSA fa

Page 25: XPug Milano - Hexagonal architecture

non COME lo fa

Page 26: XPug Milano - Hexagonal architecture
Page 27: XPug Milano - Hexagonal architecture

MVC è un’architettura?

Page 28: XPug Milano - Hexagonal architecture

MVC è un PATTERN

Page 29: XPug Milano - Hexagonal architecture

"Model-View-Controller is the concept introduced by Smalltalk's inventors (Trygve

Reenskaug and others) of encapsulating some data together with its processing (the model)

and isolate it from the manipulation (the controller) and presentation (the view) part that

has to be done on a UserInterface. reason."

http://c2.com/cgi/wiki?ModelViewController

Page 30: XPug Milano - Hexagonal architecture

il web é un’architettura?

Page 31: XPug Milano - Hexagonal architecture

NO! E’ un I/O Device

Page 32: XPug Milano - Hexagonal architecture

"Software architecture is not about databases, web servers, dependency injection, Rails, Hibernate, JSF, Struts, Spring, or any other

framework or tool. Architecture is about intent."

"When you see a web-based accounting system, the architecture of that system should scream accounting at you. The fact that it's a web

based system should be unnoticeable. After all, the web is just a delivery mechanism; and we don't want our system

architecture polluted with delivery mechanisms, databases, and other low level tools and concerns."

[https://cleancoders.com/episode/clean-code-episode-7/show]

Page 33: XPug Milano - Hexagonal architecture

public function changeUserPassword($userId, $newPassword) {

$entityManager = $this->getDoctrine()->getRepository('AppBundle:Post')->getEntityManager; $query = $entityManager->createNativeQuery('SELECT * FROM users WHERE id = ?'); $query->setParameter(1, 'xpug');

$user = $query->getResult();

if ($user->getPassword() == $newPassword) { return "You should change you password"; }

if (strlen($newPassword) < 8) { return "Password must be at least 8 chars long"; } $user->setPassword($newPassword); $entityManager->store($user);

return "Thank you, password updated”;

}

Esempio tipico

Page 34: XPug Milano - Hexagonal architecture
Page 35: XPug Milano - Hexagonal architecture

Logica di BusinessDatabase

Interfaccia Utente

SMTP

Page 36: XPug Milano - Hexagonal architecture

public function changeUserPassword($userId, $newPassword) {

$entityManager = $this->getDoctrine()->getRepository('AppBundle:Post')->getEntityManager; $query = $entityManager->createNativeQuery('SELECT * FROM users WHERE id = ?'); $query->setParameter(1, 'xpug');

$user = $query->getResult();

if ($user->getPassword() == $newPassword) { return "You should change you password"; }

if (strlen($newPassword) < 8) { return "Password must be at least 8 chars long"; } $user->setPassword($newPassword); $entityManager->store($user);

return "Thank you, password updated”;

}

Per quali motivi può cambiare?

Page 37: XPug Milano - Hexagonal architecture

public function changeUserPassword($userId, $newPassword) {

$entityManager = $this->getDoctrine()->getRepository('AppBundle:Post')->getEntityManager; $query = $entityManager->createNativeQuery('SELECT * FROM users WHERE id = ?'); $query->setParameter(1, 'xpug');

$user = $query->getResult();

if ($user->getPassword() == $newPassword) { return "You should change you password"; }

if (strlen($newPassword) < 8) { return "Password must be at least 8 chars long"; } $user->setPassword($newPassword); $entityManager->store($user);

return "Thank you, password updated”;

}

Per quali motivi può cambiare?

Page 38: XPug Milano - Hexagonal architecture

Almeno tre:• Meccanismo di persistenza

• Regole di business

• Formato di output

Page 39: XPug Milano - Hexagonal architecture

Single Responsibility Principle (SRP)

"Gather together the things that change for the same reasons. Separate those things that change for different reasons.”

Page 40: XPug Milano - Hexagonal architecture

Layered architecture

Page 41: XPug Milano - Hexagonal architecture

User Interface Layer

Application Layer

Domain Layer

Infrastructure Layer

Page 42: XPug Milano - Hexagonal architecture
Page 43: XPug Milano - Hexagonal architecture

Dependency Inversion Principle (DIP)

"High-level modules should not depend on low-level modules. Both should depend on abstractions.

Abstractions should not depend upon details. Details should depend upon abstraction."

Page 44: XPug Milano - Hexagonal architecture

Hexagonal Architecture

Page 45: XPug Milano - Hexagonal architecture

http://alistair.cockburn.us/Hexagonal+architecture

Page 46: XPug Milano - Hexagonal architecture

Application• È il cuore dell’esagono

• Contiene la logica di dominio

• È totalmente indipendente dal meccanismo di delivery (console application, REST endpoint…)

• È totalmente indipendente dai servizi di supporto (database, SMTP, AMPQ…)

Page 47: XPug Milano - Hexagonal architecture

Application - Dominio

• Aggregati, entità, valori, servizi di dominio, eventi di dominio vivono all’interno dell’esagono

• Vengono coordinati dagli use-case (Application Service) per compiere gli scopi dall'applicazione

Page 48: XPug Milano - Hexagonal architecture

Application - Porte Primarie• aka use-case, application service

• usate per guidare l’applicazione dall'esterno

• non conoscono la natura del client che le userà

• il focus è sullo scopo della conversazione, non sulla tecnologia utilizzata

Page 49: XPug Milano - Hexagonal architecture

esempio - portapublic class BookRatingUseCase implements UseCase{ private final BookCatalog catalog; private final BookRatingRepository bookRatingRepository; public BookRatingUseCase(BookCatalog catalog, BookRatingRepository bookRatingRepository) { this.catalog = catalog; this.bookRatingRepository = bookRatingRepository; } public void execute(BookRatingRequest request) { Book book = catalog.bookWithId(new BookId(request.getBookId())); guardBookNotFound(book); BookRating rate = book.rate(Rating.value(request.getRating())); bookRatingRepository.add(rate); } private void guardBookNotFound(Book book) { if (book == null) throw new BookNotFoundException(); } }

Page 50: XPug Milano - Hexagonal architecture

esempio - adapter@RestController@RequestMapping(value = "/book/{bookId}/rating") public class BookRatingController{ private final UseCase useCase; @Inject public BookRatingController(UseCase bookRatingUseCase) { this.useCase = bookRatingUseCase; } @RequestMapping(method = POST) @ResponseStatus(value = CREATED) public void rateBook(@PathVariable String bookId, @RequestBody BookRatingDTO bookRatingDTO) { useCase.execute(new BookRatingRequest(bookId, bookRatingDTO.getRating())); } @ExceptionHandler(value = BookNotFoundException.class) @ResponseStatus(value = NOT_FOUND) public void exceptionHandler(BookNotFoundException e) { }}

Page 51: XPug Milano - Hexagonal architecture

Application - Porte Secondarie

• usate dagli abitanti dell’esagono per comunicare con il mondo esterno

• vengono definite come interfacce

• il focus deve essere sullo scopo della conversazione, e non sulla tecnologia sottostante

Page 52: XPug Milano - Hexagonal architecture

esempio - portapublic interface BookCatalog{ Book bookWithId(BookId bookId); }

Page 53: XPug Milano - Hexagonal architecture

esempio - adapterpublic class InMemoryBookCatalog implements BookCatalog{ private final List<Book> books; public InMemoryBookCatalog(Book... books) { this.books = asList(books); } @Override public Book bookWithId(BookId bookId) { for (Book book : books) { if (book.hasId(bookId)) return book; } return null; } }

Page 54: XPug Milano - Hexagonal architecture

Demo time!

Page 55: XPug Milano - Hexagonal architecture

Hexagonal Books

Application

REST

In Memory

Cons

ole

Mysql

Page 56: XPug Milano - Hexagonal architecture

Vediamo un po’ di codice

Page 57: XPug Milano - Hexagonal architecture

Vantaggi• È possibile concentrarsi da subito sul dominio del problema

• Differire le decisioni riguardo I/O devices

• Testare in unità il dominio

• Erogare l’applicazione su canali differenti (rest, console, acceptance

test, stream-processing ecc)

Page 58: XPug Milano - Hexagonal architecture

Vantaggi / 2

• Non occorre sposare il framework MVC

• Maggiore espressività nell'esagono

Page 59: XPug Milano - Hexagonal architecture

Q&A

Page 60: XPug Milano - Hexagonal architecture

Grazie!

Page 61: XPug Milano - Hexagonal architecture