A proposta desta apresentação é mostrar uma alternativa para construção de aplicações com Ruby on Rails que dá ênfase a modelagem de domínio, separando o código que resolve o problema de negócio do código do framework.
ASP.NET Core is a significant redesign of ASP.NET. This topic introduces the new concepts in ASP.NET Core and explains how they help you develop modern web apps.
The document discusses the use of the keywords super and this in Java. Super allows subclasses to access methods and fields of the parent class that have been overridden or hidden. It has two forms - to call the parent constructor or to access a hidden parent member. This refers to the current object and is used to avoid name conflicts between instance variables and local variables.
Introduction to Spring's Dependency InjectionRichard Paul
This document provides an overview of dependency injection in Spring. It defines dependency injection as a form of inversion of control where objects are provided to classes rather than having classes create their own dependencies. It discusses the benefits of dependency injection such as loose coupling, easy switching of implementations, and enhanced testability. It also compares constructor injection and setter injection and describes how to configure dependency injection using XML, annotations, and Java configuration in Spring.
Nowadays traditional layered monolithic architecture in Java world is not so popular as 5-10 years ago. I remember how we wrote tons of code for each layer repeating almost the same parts for every application. Add unit and integration testing to understand how much time and efforts has been spent on repeatable work. All cool ideas around DDD (domain driven design) and Hexagonal Architecture was just a nice theory because reality hasn’t allow us to implement it easily. Even Dependency Injection with Spring framework was completely focused on traditional layered approach, not even talking about JavaEE platform.
Today we have Spring Boot ecosystem covering most of our needs for integration with almost all possible technologies and microservices architectural trend, enabling completely new approach to build Java applications around domain model. It is so natural to build Java domain-oriented services and connect them with external world using ports and adapters, that Hexagonal Architecture is almost enabled by default. You just need to switch your way of thinking…
Hexagonal architecture is a software architecture model created in 2005 to help isolate domain/business logic from external interfaces and infrastructure. It focuses on separating core domain functions from outside influences like databases, user interfaces, and networking to allow independent development and testing of each layer. Adapters act as intermediaries between the isolated domain/core and external components like databases or web services, allowing for flexibility in how the core interacts with these external elements. Hexagonal architecture can help with high testability, loose coupling between layers, and scalability by allowing external ports to be scaled independently.
Building RESTful applications using Spring MVCIndicThreads
REST is an alternate and simpler approach for implementing WebServices. It is based on the HTTP protocol and hence leverages a lot of existing infrastructures. It uses an uniform interface thus making it easy to build client applications. In this session we will look at the fundamental concepts behind REST (Resource, URI, Stateless Conversation ..) and how to apply it in the context of a real applcation. We will also discuss the pros & cons of RESTful vs Soap based webservices. We will discuss the design of RESTful application and then look at how to implement it using Spring MVC.
The document provides an overview of object-oriented programming concepts and Java programming. It discusses key OOP concepts like abstraction, encapsulation, inheritance, polymorphism and classes. It then covers the history and development of Java, describing how it was initially created at Sun Microsystems to develop software for consumer electronics but was later targeted towards internet programming. The document also lists some of Java's key characteristics like being simple, secure, portable, object-oriented, robust and multithreaded.
The document discusses Swagger, an open source API documentation framework. It describes how Swagger is used to document REST APIs and provides an interactive UI. It then outlines how to add Swagger documentation to a Spring Boot project using Springfox, including adding dependencies, configuring Swagger, and annotating controllers. The document demonstrates how Swagger UI allows developers to easily view and test documented APIs in the browser.
Object Oriented Concept Static vs. Non StaticOXUS 20
Static is not the true intend of Object Oriented Design and Concept.
For instance, we turn a LAMP "off" it does not suppose to turn the LAMPS of the entire world goes "off".
Basic java important interview questions and answers to secure a jobGaruda Trainings
P2Cinfotech is one of the leading, Online IT Training facilities and Job Consultant, spread all over the world. We have successfully conducted online classes on various Software Technologies that are currently in Demand. To name a few, we provide quality online training for QA, QTP, Manual Testing, HP LoadRunner, BA, Java Technologies, SEO, Web Technologies, .NET, Oracle DBA etc.
This document provides an introduction to Node.js. It discusses why JavaScript can be strange, but explains that JavaScript is relevant as the language of the web. It then discusses what Node.js is and its event-driven, non-blocking architecture. Popular Node.js applications like HTTP servers, REST APIs, and web sockets are mentioned. Examples are provided of building a simple web app with Express and Jade, a REST API with Restify, and using web sockets with Socket.io. The document also discusses using Mongoose with MongoDB for data modeling.
20 most important java programming interview questionsGradeup
The document discusses 20 important Java programming interview questions. It covers topics such as the differences between interfaces and abstract classes, when to use abstract classes versus interfaces, what the Serializable interface does, how to force garbage collection, the differences between StringBuffer and StringBuilder, checked and unchecked exceptions, how Java allocates stack and heap memory, Java reflection, the Java Virtual Machine, the differences between JDK and JRE, and more.
This document provides a summary of MongoDB and Mongoose 101 presented at a Phoenix MongoDB Meetup. It introduces the presenter and his background. It then provides a high-level overview of MongoDB and compares SQL and MongoDB terminology. The remainder of the document demonstrates basic CRUD operations in MongoDB using the Mongo shell and introduces Mongoose, an ORM for MongoDB, demonstrating how to define schemas and models and perform queries and validations. It also discusses subdocuments and population features in Mongoose.
Slides of the talk I gave at ConFoo Montréal 2019 about "Hexagonal Architecture".
Hexagonal Architecture, Clean Architecture, Domain-Driven Design… You may have heard about them. Let's start from scratch in this session and go beyond the buzzwords. We'll go together though these ideas to understand how you can improve the maintainability of your projects', either greenfield or legacy.
This document provides a quick reference to Java programming concepts including:
1. The basic syntax for a Java application with a main method and how to compile and run it.
2. Primitive data types in Java and their sizes.
3. Keywords, naming conventions, and basic syntax for classes, methods, and variables.
4. Common Java constructs like if/else statements, loops, arrays, and exceptions.
Spring boot is a suite, pre-configured, pre-sugared set of frameworks/technologies to reduce boilerplate configuration providing you the shortest way to have a Spring web application up and running with smallest line of code/configuration out-of-the-box.
The document provides an introduction to web APIs and REST. It defines APIs as methods to access data and workflows from an application without using the application itself. It describes REST as an architectural style for APIs that uses a client-server model with stateless operations and a uniform interface. The document outlines best practices for REST APIs, including using HTTP verbs like GET, POST, PUT and DELETE to perform CRUD operations on resources identified by URIs. It also discusses authentication, authorization, security concerns and gives examples of popular REST APIs from Facebook, Twitter and other services.
The document discusses hexagonal architecture and how it can be applied to PHP applications. It begins by defining software architecture and its importance. It then explains hexagonal architecture, which separates an application into distinct layers including domain, application, and infrastructure layers. The layers are decoupled via defined boundaries and interfaces. Commands are used to communicate between layers and are handled by command buses and handlers. Examples are given of implementing repositories, commands and handlers to follow this pattern in a PHP application.
James Gosling initiated the Java language project in 1991. The first public implementation of Java was released as Java 1.0 in 1995. Oracle acquired Sun Microsystems in 2010. Java is an object-oriented programming language that is platform independent and promises "Write Once, Run Anywhere". A key component of Java is the Java Virtual Machine (JVM) which is responsible for memory allocation and provides a runtime environment for executing Java bytecode.
Spring Boot is a framework for creating stand-alone, production-grade Spring-based applications that can be started using java -jar without requiring any traditional application servers. It is designed to get developers up and running as quickly as possible with minimal configuration. Some key features of Spring Boot include automatic configuration, starter dependencies to simplify dependency management, embedded HTTP servers, security, metrics, health checks and externalized configuration. The document then provides examples of building a basic RESTful web service with Spring Boot using common HTTP methods like GET, POST, PUT, DELETE and handling requests and responses.
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Steve Pember
In this presentation we will present the general philosophy of Clean Architecture, Hexagonal Architecture, and Ports & Adapters: discussing why these approaches are useful and general guidelines for introducing them to your code. Chiefly, we will show how to implement these patterns within your Spring (Boot) Applications. Through a publicly available reference app, we will demonstrate what these concepts can look like within Spring and walkthrough a handful of scenarios: isolating core business logic, ease of testing, and adding a new feature or two.
Functions in PHP allow programmers to organize code into reusable blocks. There are built-in and user-defined functions. User-defined functions use the function keyword and can accept arguments, return values, and be called elsewhere in the code. Functions can pass arguments by value, where changes inside the function don't affect the original variable, or by reference, where changes are reflected outside the function. Functions can also have default argument values and static variables that retain their value between calls.
The document outlines an online training course for Angular 10 that covers fundamental concepts like TypeScript, Angular fundamentals, NgRx, server-side integration with Node and Express, Angular Material, PrimeNG, and a final e-commerce project. The 50-day, 100-hour course includes daily live and hands-on training, video lessons, project files, and lifetime access for 6000 INR or $85. Key topics include Angular architecture, components, routing, HTTP requests, reactive forms, state management with NgRx, REST APIs, authentication, and deployment.
SOLID Principles and The Clean ArchitectureMohamed Galal
This presentation is held at @blablaconnect Cairo office, Monday 31 December 2018.
In this presentation we will discuss the following topics:
- SOLID principles.
- Design Pattern vs. Clean Architecture.
- Successful software architecture characteristics.
- The Clean Architecture.
- Real life example.
Spring tutorial for beginners - Learn Java Spring Framework version 3.1.0 starting from environment setup, inversion of control (IoC), dependency injection, bean scopes, bean life cycle, inner beans, autowiring, different modules, aspect oriented programming (AOP), database access (JDBC), Transaction Management, Web MVC framework, Web Flow, Exception handling, EJB integration and Sending email etc.
1) O documento descreve como o Domain Driven Design (DDD) e o Strategic Design estão ajudando a modernizar um legado de sistema para uma empresa de medicina do trabalho.
2) O sistema começou simples mas cresceu de forma desorganizada ao longo de 5 anos, levando a muitos bugs. O DDD está sendo usado para dividir o domínio em Bounded Contexts e melhorar a arquitetura.
3) A estratégia envolve isolar funcionalidades em módulos/libs, definir interfaces para comunicação com o legado, e
Como DDD e Strategic Design estão nos ajudando a modernizar um LegadoLuiz Costa
O objetivo desta palestra é mostrar como é possível evoluir e reescrever partes de uma aplicação legada com mais 5 anos em produção utilizando técnicas de uma parte Domain Driven Design conhecida como Strategic Design. É uma aplicação web escrita em Python e Django que suporta a operação de um grupo focado em medicina do trabalho, com clínicas espalhadas pelo país.
Nesta palestra vamos mostrar uma abordagem que pode ajudar times que precisam lidar com aplicações legadas grandes e complexas no caminho da modernização.
The document discusses Swagger, an open source API documentation framework. It describes how Swagger is used to document REST APIs and provides an interactive UI. It then outlines how to add Swagger documentation to a Spring Boot project using Springfox, including adding dependencies, configuring Swagger, and annotating controllers. The document demonstrates how Swagger UI allows developers to easily view and test documented APIs in the browser.
Object Oriented Concept Static vs. Non StaticOXUS 20
Static is not the true intend of Object Oriented Design and Concept.
For instance, we turn a LAMP "off" it does not suppose to turn the LAMPS of the entire world goes "off".
Basic java important interview questions and answers to secure a jobGaruda Trainings
P2Cinfotech is one of the leading, Online IT Training facilities and Job Consultant, spread all over the world. We have successfully conducted online classes on various Software Technologies that are currently in Demand. To name a few, we provide quality online training for QA, QTP, Manual Testing, HP LoadRunner, BA, Java Technologies, SEO, Web Technologies, .NET, Oracle DBA etc.
This document provides an introduction to Node.js. It discusses why JavaScript can be strange, but explains that JavaScript is relevant as the language of the web. It then discusses what Node.js is and its event-driven, non-blocking architecture. Popular Node.js applications like HTTP servers, REST APIs, and web sockets are mentioned. Examples are provided of building a simple web app with Express and Jade, a REST API with Restify, and using web sockets with Socket.io. The document also discusses using Mongoose with MongoDB for data modeling.
20 most important java programming interview questionsGradeup
The document discusses 20 important Java programming interview questions. It covers topics such as the differences between interfaces and abstract classes, when to use abstract classes versus interfaces, what the Serializable interface does, how to force garbage collection, the differences between StringBuffer and StringBuilder, checked and unchecked exceptions, how Java allocates stack and heap memory, Java reflection, the Java Virtual Machine, the differences between JDK and JRE, and more.
This document provides a summary of MongoDB and Mongoose 101 presented at a Phoenix MongoDB Meetup. It introduces the presenter and his background. It then provides a high-level overview of MongoDB and compares SQL and MongoDB terminology. The remainder of the document demonstrates basic CRUD operations in MongoDB using the Mongo shell and introduces Mongoose, an ORM for MongoDB, demonstrating how to define schemas and models and perform queries and validations. It also discusses subdocuments and population features in Mongoose.
Slides of the talk I gave at ConFoo Montréal 2019 about "Hexagonal Architecture".
Hexagonal Architecture, Clean Architecture, Domain-Driven Design… You may have heard about them. Let's start from scratch in this session and go beyond the buzzwords. We'll go together though these ideas to understand how you can improve the maintainability of your projects', either greenfield or legacy.
This document provides a quick reference to Java programming concepts including:
1. The basic syntax for a Java application with a main method and how to compile and run it.
2. Primitive data types in Java and their sizes.
3. Keywords, naming conventions, and basic syntax for classes, methods, and variables.
4. Common Java constructs like if/else statements, loops, arrays, and exceptions.
Spring boot is a suite, pre-configured, pre-sugared set of frameworks/technologies to reduce boilerplate configuration providing you the shortest way to have a Spring web application up and running with smallest line of code/configuration out-of-the-box.
The document provides an introduction to web APIs and REST. It defines APIs as methods to access data and workflows from an application without using the application itself. It describes REST as an architectural style for APIs that uses a client-server model with stateless operations and a uniform interface. The document outlines best practices for REST APIs, including using HTTP verbs like GET, POST, PUT and DELETE to perform CRUD operations on resources identified by URIs. It also discusses authentication, authorization, security concerns and gives examples of popular REST APIs from Facebook, Twitter and other services.
The document discusses hexagonal architecture and how it can be applied to PHP applications. It begins by defining software architecture and its importance. It then explains hexagonal architecture, which separates an application into distinct layers including domain, application, and infrastructure layers. The layers are decoupled via defined boundaries and interfaces. Commands are used to communicate between layers and are handled by command buses and handlers. Examples are given of implementing repositories, commands and handlers to follow this pattern in a PHP application.
James Gosling initiated the Java language project in 1991. The first public implementation of Java was released as Java 1.0 in 1995. Oracle acquired Sun Microsystems in 2010. Java is an object-oriented programming language that is platform independent and promises "Write Once, Run Anywhere". A key component of Java is the Java Virtual Machine (JVM) which is responsible for memory allocation and provides a runtime environment for executing Java bytecode.
Spring Boot is a framework for creating stand-alone, production-grade Spring-based applications that can be started using java -jar without requiring any traditional application servers. It is designed to get developers up and running as quickly as possible with minimal configuration. Some key features of Spring Boot include automatic configuration, starter dependencies to simplify dependency management, embedded HTTP servers, security, metrics, health checks and externalized configuration. The document then provides examples of building a basic RESTful web service with Spring Boot using common HTTP methods like GET, POST, PUT, DELETE and handling requests and responses.
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Steve Pember
In this presentation we will present the general philosophy of Clean Architecture, Hexagonal Architecture, and Ports & Adapters: discussing why these approaches are useful and general guidelines for introducing them to your code. Chiefly, we will show how to implement these patterns within your Spring (Boot) Applications. Through a publicly available reference app, we will demonstrate what these concepts can look like within Spring and walkthrough a handful of scenarios: isolating core business logic, ease of testing, and adding a new feature or two.
Functions in PHP allow programmers to organize code into reusable blocks. There are built-in and user-defined functions. User-defined functions use the function keyword and can accept arguments, return values, and be called elsewhere in the code. Functions can pass arguments by value, where changes inside the function don't affect the original variable, or by reference, where changes are reflected outside the function. Functions can also have default argument values and static variables that retain their value between calls.
The document outlines an online training course for Angular 10 that covers fundamental concepts like TypeScript, Angular fundamentals, NgRx, server-side integration with Node and Express, Angular Material, PrimeNG, and a final e-commerce project. The 50-day, 100-hour course includes daily live and hands-on training, video lessons, project files, and lifetime access for 6000 INR or $85. Key topics include Angular architecture, components, routing, HTTP requests, reactive forms, state management with NgRx, REST APIs, authentication, and deployment.
SOLID Principles and The Clean ArchitectureMohamed Galal
This presentation is held at @blablaconnect Cairo office, Monday 31 December 2018.
In this presentation we will discuss the following topics:
- SOLID principles.
- Design Pattern vs. Clean Architecture.
- Successful software architecture characteristics.
- The Clean Architecture.
- Real life example.
Spring tutorial for beginners - Learn Java Spring Framework version 3.1.0 starting from environment setup, inversion of control (IoC), dependency injection, bean scopes, bean life cycle, inner beans, autowiring, different modules, aspect oriented programming (AOP), database access (JDBC), Transaction Management, Web MVC framework, Web Flow, Exception handling, EJB integration and Sending email etc.
1) O documento descreve como o Domain Driven Design (DDD) e o Strategic Design estão ajudando a modernizar um legado de sistema para uma empresa de medicina do trabalho.
2) O sistema começou simples mas cresceu de forma desorganizada ao longo de 5 anos, levando a muitos bugs. O DDD está sendo usado para dividir o domínio em Bounded Contexts e melhorar a arquitetura.
3) A estratégia envolve isolar funcionalidades em módulos/libs, definir interfaces para comunicação com o legado, e
Como DDD e Strategic Design estão nos ajudando a modernizar um LegadoLuiz Costa
O objetivo desta palestra é mostrar como é possível evoluir e reescrever partes de uma aplicação legada com mais 5 anos em produção utilizando técnicas de uma parte Domain Driven Design conhecida como Strategic Design. É uma aplicação web escrita em Python e Django que suporta a operação de um grupo focado em medicina do trabalho, com clínicas espalhadas pelo país.
Nesta palestra vamos mostrar uma abordagem que pode ajudar times que precisam lidar com aplicações legadas grandes e complexas no caminho da modernização.
Modular Monoliths - Como é possível organizar sua aplicação para habilitar um...Luiz Costa
O objetivo desta palestra é mostrar como é possível construir uma aplicação baseada na idéia de MonolithFirst e atrasar a decisão de separar em microserviços. A ideia de modular monoliths vem da organização e separação da sua aplicação em módulos ou componentes autônomos que se relacionam entre si, mas estão dentro de uma mesma base de código. Nesta palestra será mostrado como identificar e separar estes módulos, além de um processo que permite extrair um módulo e distribuir como um microserviço.
O documento discute programação reativa e serverless no Azure. Na primeira parte, fornece contexto histórico sobre a evolução dos sistemas e mudanças nos paradigmas de programação. A segunda parte explica conceitos de programação reativa e como ela se relaciona com programação funcional. A terceira parte introduz o tópico de serverless e discute seu espectro de uso na nuvem.
Este documento apresenta o framework CakePHP para desenvolvimento rápido de aplicações web, usando como estudo de caso um sistema gerenciador de produtos e serviços. Descreve as principais características do CakePHP como MVC, ORM e geração automática de CRUD e como estas funcionalidades foram aplicadas no caso de uso.
O documento resume uma apresentação sobre o framework Struts 2 e seu uso no projeto Minha Casa Minha Vida. O documento discute o que é Struts, seu histórico, recursos principais e como foi usado no projeto, com foco na arquitetura MVC e validação.
O documento resume o currículo de Eric Gallardo, um profissional de TI brasileiro com quase 20 anos de experiência em projetos para internet e gestão corporativa utilizando diversas linguagens e metodologias como .NET, Java, Scrum e ITIL. O treinamento aborda conceitos e frameworks como ASP.NET, MVC, WebForms, Entity Framework e AJAX/jQuery além de ferramentas como Visual Studio e plugins.
O documento descreve um curso intermediário de C# que aborda padrões de projeto como Transfer Object, Data Access Object, Singleton e MVC. Também apresenta tópicos como tipos primitivos, estruturas de dados, acesso a dados, formulários, relatórios e projetos de instalação. Explica alguns padrões de projeto com exemplos como TO para transferência de dados, DAO para acesso a dados e Singleton para garantir uma única instância de uma classe. Por fim, descreve os passos para desenvolver um sistema de cadastro de produtos e vendas
[DTC21] Thiago Lima - Do Zero ao 100 no Mundo de MicroservicesDeep Tech Brasil
Thiago Lima é um empreendedor e especialista em tecnologia com mais de 30 anos de experiência desenvolvendo e liderando equipes de tecnologia. Ele falará sobre microsserviços, desde a decomposição de sistemas até práticas de monitoramento e resiliência.
O documento discute princípios arquiteturais e boas práticas para o desenvolvimento de microsserviços, incluindo Domain-Driven Design, 12 Factor Apps, testes, resiliência e automação.
1) O documento fornece 10 dicas para a implementação do Oracle Application Server em ambientes corporativos, incluindo determinar requisitos, adotar uma topologia de referência e antecipar problemas conhecidos.
2) É recomendado formalizar um mediador entre as áreas envolvidas na instalação para facilitar a comunicação.
3) Também é aconselhável estabelecer pontos de controle durante a instalação e configuração para evitar atrasos.
O documento discute as arquiteturas de micro serviços e monolítica, comparando seus prós e contras. A arquitetura de micro serviços divide a aplicação em vários serviços independentes que se comunicam através de APIs, permitindo maior escalabilidade e falhas isoladas. Porém requer mais esforço de gerenciamento dos serviços. Não há modelo certo, dependendo do tamanho e necessidades da aplicação.
O documento discute modelos de arquitetura de software, padrões de projeto e o framework Struts. Aborda os modelos de 2, 3 e 4 camadas, o padrão Model-View-Controller (MVC), padrões como Front Controller e patterns como o DAO. Explica como frameworks como Struts implementam esses padrões e discute casos de uso, modelagem, fluxos e o futuro das certificações em CMM.
1. O documento discute conceitos e tecnologias para desenvolvimento front-end como estado, APIs, frameworks e conclusões.
2. É apresentada uma comparação entre estilos imperativo e funcional e entre APIs do tipo RPC, REST e GRAPH.
3. Frameworks como Angular, React e Polymer são discutidos e a conclusão é que é importante separar a lógica da aplicação dos frameworks.
O documento discute testes em webservices, mencionando conceitos como SOAP, REST, XML, JSON e tipos de testes como contrato, funcional e performance. Também apresenta ferramentas como parsers online e links úteis sobre o tema.
1. O documento discute técnicas para escalar aplicações React e TypeScript, incluindo estrutura de projetos, boas práticas de código, testes e monitoramento.
2. O autor tem experiência desenvolvendo sites com milhões de visitas diárias e discute como projetos podem crescer rapidamente sem problemas de desempenho ou manutenibilidade.
3. Escalabilidade envolve estruturar o código e projeto para que novos desenvolvedores possam entender facilmente, adicionar novas funcionalidades rapid
Escalabilidade via Software no ExpressoV3Flávio Lisboa
Apresentaremos o projeto ExpressoV3, suas funcionalidades, arquitetura e comunidade, mostraremos o cenário de expansão de usuários e detalharemos as soluções arquiteturais projetadas para escalar a aplicação, que podem servir para outras aplicações PHP.
O documento discute a arquitetura de microserviços, definindo-a como um estilo arquitetural que enfatiza a decomposição de aplicações em microserviços de baixo acoplamento gerenciados por equipes multifuncionais. Também aborda os pré-requisitos de arquitetura para microserviços, como a computação distribuída, a orquestração versus coreografia e o uso de mensageria.
5. Components within the layered
architecture pattern are organized
into horizontal layers, each layer
performing a specific role within the
application (e.g., presentation logic or
business logic).
Software Architecture Patterns, Mark Richards
https://www.oreilly.com/library/view/software-architecture-patterns/9781491971437/
6. Na versão mais “restrita” deste
pattern, as camadas
superiores só acessam as
inferiores passando pela
camada seguinte.
7. Existem algumas variações,
por exemplo, quando algumas
camadas podem acessar
diretamente outras camadas
sem passar pela seguinte.
Neste caso diz-se que existem
camadas “abertas”.
20. Hexagonal Architecture, Alistair Cockburn
https://bit.ly/2XBQHNx
Allow an application to equally be driven
by users, programs, automated test or
batch scripts, and to be developed and
tested in isolation from its eventual run-
time devices and databases.
23. Each face of the hexagon (port)
represents some "reason" the application
is trying to talk with the outside world.
Events arrive from the outside world at a
port. The adapter converts it into a
usable procedure call or message and
passes it to the application. The
application is blissfully ignorant of the
nature of the input device…
Ports and Adapters Architecture, Alistair Cockburn
http://wiki.c2.com/?
PortsAndAdaptersArchitecture
24. Ports and Adapters Architecture, Alistair Cockburn
http://wiki.c2.com/?
PortsAndAdaptersArchitecture
Each face of the hexagon (port)
represents some "reason" the application
is trying to talk with the outside world.
Events arrive from the outside world at a
port. The adapter converts it into a
usable procedure call or message and
passes it to the application. The
application is blissfully ignorant of the
nature of the input device…
25. O adaptador converte a
mensagem e manipula ou
delega para os objetos de
domínio
uma aplicação pode ter
várias portas e isso não
se limita ao número de
lados do hexágono
35. Screaming Architecture, Robert Martin
https://blog.cleancoder.com/uncle-bob/2011/09/30Screaming-Architecture.html
Architectures are not (or should not) be
about frameworks. Architectures should
not be supplied by frameworks.
Frameworks are tools to be used, not
architectures to be conformed to. If you
architecture is based on frameworks,
then it cannot be based on your use
cases.
36. Screaming Architecture, Robert Martin
https://blog.cleancoder.com/uncle-bob/2011/09/30Screaming-Architecture.html
Architectures are not (or should not) be
about frameworks. Architectures should
not be supplied by frameworks.
Frameworks are tools to be used, not
architectures to be conformed to. If you
architecture is based on frameworks,
then it cannot be based on your use
cases.
38. Your architectures should tell readers
about the system, not about the
frameworks you used in your system.
If you are building a health-care
system, then when new programmers
look at the source repository, their first
impression should be: “Oh, this is a
health-care system”.
Screaming Architecture, Robert Martin
https://blog.cleancoder.com/uncle-bob/2011/09/30Screaming-Architecture.html
47. O código de negócio fica dentro da
pasta application. Dentro da pasta,
todo acesso ao framework é feito por
adaptadores.
48. O código da aplicação web, escrita em rails, fica dentro de web
app. Esta pasta é a implementação de um delivery mechanism.
O código de negócio, que vive dentro de application, é
acessado através de portas.
50. alguns dos possíveis módulos de uma aplicação que
resolve o problema de vacinação domiciliar
51. o mesmo objeto de
domínio em diferentes
contextos ou módulos
52. Paciente
Atendimento
+ qual nome, nascimento…?
+ qual dia do agendamento?
+ qual endereço de atendimento?
Paciente
Vacinação
+ como a caderneta de vacinação
está organizada?
+ qual a próxima vacina?
+ qual vacina foi aplicada?
Paciente
Financeiro
+ qual custo das vacinas aplicadas?
+ alguma condição de desconto?
+ qual meio de pagamento utilizado?
É responsabilidade de cada
contexto modelar os dados da
melhor maneira, de acordo com
as suas responsabilidades.
53. cada módulo é como se
fosse uma implementação
do padrão hexagonal
58. implementação de um use case
O fluxo de execução
é simples e limpo
As dependências são
injetadas no
construtor
Usa um factory
method* para manter
o encapsulamento e
diminuir o acoplamento
com o objeto cliente
* https://en.wikipedia.org/wiki/Factory_method_pattern
application/src
60. conectando a web app com o application
Aqui o factory method é
usado para instanciar o use
case.
A interface pública do use case é usada como
Port para acessar o código da application
* https://en.wikipedia.org/wiki/Factory_method_pattern
web-app/app/controllers
62. objetos de domínio são escritos em código ruby puro
(PORO*)
Não existe nenhuma
relação direta com o
Active Record
*http://blog.jayfields.com/2007/10/ruby-poro.html
64. Nas implementações padrão do rails,
o model é uma subclasse de
ApplicationRecord, isso faz com que
o acoplamento com o banco de dados
seja bem alto.
65. O domain object é separado do
Model e o seu ciclo de vida é
controlado por um Repositório*.
O repositório é responsável por
executar as consultas (queries),
e mapear os objetos de domínio.
Para isso pode ter a
colaboração de uma Factory*.
O Model tem a responsabilidade de
garantir a consistência dos dados,
de acordo com o modelo relacional.
Pode definir algumas queries e ter
validações de dados
O domain object é quem tem a
implementação das lógicas de
negócio.
*https://martinfowler.com/eaaCatalog/repository.html
66. Um único Model pode dar origem a um modelo de domínio bem mais
complexo. Neste caso, todos os dados do domain model são persistidos
na mesma tabela (Rails Model) do banco de dados.
67. implementação de um repositório
Aqui o model é usado para tirar
vantagem do Active Record.
Uma factory é usada para fazer
a construção do objeto de
domínio.
.active_nurses é uma query que
está encapsulada no Model.
O save também delega
para o Active Record.
70. para uma proposta de implementação
O controlador acessa os módulos através de uma porta que
expõe a interface pública de um caso de uso.
O repositório encapsula o acesso
aos models, funcionando como
mais um adaptador.
A implementação do caso de
uso atua como um adaptador.
71. para uma proposta de implementação
inside outside
outside
O controlador acessa os módulos através de uma porta que
expõe a interface pública de um caso de uso.
O repositório encapsula o acesso
aos models, funcionando como
mais um adaptador.
A implementação do caso de
uso atua como um adaptador.
73. Deve permitir ao paciente
agendar a aplicação de
vacina.
Ao fazer o agendamento
deve-se efetuar o
pagamento e reservar o
estoque dos produtos
agendados.
74. Deve permitir ao paciente
agendar a aplicação de
vacina.
Ao fazer o agendamento
deve-se efetuar o
pagamento e reservar o
estoque dos produtos
agendados.
79. O ideal é que um contexto
só exponha objetos de
fronteira. Ex: Use Cases,
Services ou Repositories
Se precisar retornar um conjunto de
dados mais complexo, dê
preferência para Hashs ou Tuplas
Mantenha o domain model
protegido dentro do
contexto. O ideal é não
deixar “vazar" do contexto
os objetos de domínio
86. construa uma
arquitetura que te
permita atrasar as
decisões
https://8thlight.com/blog/uncle-bob/2011/11/22/Clean-Architecture.html
94. contexto de pagamento como microsserviço
O único ponto de contato com o contexto de
pagamento no agendamento era o objeto de fronteira
Pagamento. Este objeto vai precisar ser alterado e,
em vez de chamar o contexto diretamente, vamos
introduzir uma service layer para implementar a
chamada remota ao microsserviço de pagamento
O contexto de pagamento foi extraído e
adicionado em uma nova aplicação rails. Foi
necessário expor uma api para disponibilizar
o acesso aos casos de uso. Neste caso,
provavelmente os respositórios deverão ser
alterados para conectar no banco de dados
diferente.
95. contexto de pagamento como microsserviço
O único ponto de contato com o contexto de
pagamento no agendamento era o objeto de fronteira
Pagamento. Este objeto vai precisar ser alterado e,
em vez de chamar o contexto diretamente, vamos
introduzir uma service layer para implementar a
chamada remota ao microsserviço de pagamento
O contexto de pagamento foi extraído e
adicionado em uma nova aplicação rails. Foi
necessário expor uma api para disponibilizar
o acesso aos casos de uso. Neste caso,
provavelmente os respositórios deverão ser
alterados para conectar no banco de dados
diferente.
96. como extrair o contexto de
Gestão de Estoque?
Como lidar com o Domain Event AgendamentoCriado?
98. contexto de estoque como microsserviço
O contexto de agendamento continua publicando o domain event
AgendamentoCriado da mesma forma que antes, nada muda aqui.
O Event Handler original é substituído por
outro que publica o evento em um Broker de
mensagem. Ex: RabbitMQ, Kafka, ActveMQ
No microsserviço de estoque, é necessário adicionar
na ACL, handlers que serão estimulados pelas
mensagens entregues pelo broker. Estes handlers,
delegam a execução para os caso de uso.
99. O contexto de agendamento continua publicando o domain event
AgendamentoCriado da mesma forma que antes, nada muda aqui.
O Event Handler original é substituído por
outro que publica o evento em um Broker de
mensagem. Ex: RabbitMQ, Kafka, ActveMQ
No microsserviço de estoque, é necessário adicionar
na ACL, handlers que serão estimulados pelas
mensagens entregues pelo broker. Estes handlers,
delegam a execução para os caso de uso.
contexto de estoque como microsserviço