Application Architecture
2014
Lars-Erik Kindblad
Senior Consultant
& Head Of Microsoft
Community Of Practice
Feature Delivery For Most Software Projects
Project Progress
• Complex and messy code
• Code and logic is duplicated
• No ...
Ideal Feature Delivery
Project Progress
Agenda
Testable code
 Inversion of Control
Maintainable code with less duplication
 Single Responsibility Principle
 ...
Inversion Of Control
Make code loosely coupled
Make unit testing possible
Traditional Code
Inversion Of Control
Traditional code
Main class UserCreator
CreateUser
DbCommand
1. Creates
2. Creates
Inversion of control code
Main class
Us...
Dependency Injection - Constructor Injection
Dependency Injection - Interface Injection
Dependency Injection - Setter Injection
Static Service Locator
Injected Service Locator
Which Patterns To Use
Traditional Code
Dependency Injection - Constructor Injection
Dependency Injection - Interface Injection
Dependency Injection - Setter Injection
Static Service Locator
Injected Service Locator
When To Use Which
Patterns
Always Use Dependency Injection – Constructor Injection
...except
Facade Classes
Dependency Injection
Service Locator
Loops
Dependency Injection
Service Locator
Base Classes
Dependency Injection
Service Locator
Unknown Types At Compile Time
Service Locator
Summary
Constructor Injection Injected Service Locator
Facade classes
(WCF Services,
MVC Controllers)
X
Loops X X
Base cla...
Inversion Of Control (IOC) Container
A framework that can automatically create an instance of a given type with
all the r...
Configuration
Must register what types the container can resolve
Types are registered with a life time manager
 PerCont...
Where To Plugin
An IOC container should be created and initialized in the presentation
layer or or above (DependencyResol...
Unity Example 1/3
Unity Example 2/3
Unity Example 3/3
Summary
Use an IOC Container to create type instances when using inversion of
control
Only the presentation layer should...
Single Responsibility Principle
Single Responsibility Principle = SRP
1 of the 5 SOLID principles
”A class or module sh...
The God Object
A God object is an object that knows too much or does too much
The opposite of the SRP
Single Responsibility Objects
Current responsibilities:
• Facade class
• Input validation
• Talks to a database
• Sends e-mail
Refactored To SRP
UserManager
CreateUser
GetUser
DeleteUser
Refactored UserManager
Responsibility
• Facade class
Refactor GetUser & DeleteUser
Responsibility
• Return the user from the
database
Responsibility
• Delete the user from the...
Refactored to CreateUser
Responsibility
• Input validation
• Create the user in the
database
• Send confirmation e-mail
Future Refactoring
Split into multiple classes when the code increases in size
CreateUser
CreateUserDbCommand
SendEmailCo...
Summary
A class following the single responsibility principle is a class that does only
one thing and has only one reason...
Code Duplication – Example #1
Duplicated code
Extract Method Principle - Refactored
Code Duplication – Example #2
Duplicated code
Execute Around Method Pattern - Refactored
Execute Around Method - Example #2
Domain
Model
Domain Services
Presentation
Application Services
Infrastructure
Frameworks and external
endpoint integration...
Onion Architecture Flattened
Presentation
Application Services
Domain Services
Database, Web Service,
Queue, SMTP server e...
The Use Case – Open New Account
Create new account in database
and return account number
Is personal number empty?
Is the ...
Dependency Resolution
Domain
Model
Domain Services
Presentation
Application Services
Infrastructure
AccountController
Data...
Process Flow
AccountController
OpenNewAccountUseCase
CreateAccountDbCommand
CreditCheckService
GetTotalDebtForCustomer-
Se...
Alternatives – 3-Layered Architecture
Where are the use cases?
Presentation
Domain Services
Domain
Model
Database, Web Se...
Alternatives – 4-Layered Architecture
Must always go through domain
layer – domain layer will get
non-domain code
All re...
Alternatives – 4-Layered Architecture – Non-Strict
The application- and domain
logic is tightly coupled to the
infrastruc...
The Use Cases
Open new account
View accounts
Latest transactions
Single payment
Multiple payments
International payment
Vi...
Group Into Components
Account
• Open new
account
• View
accounts
• Latest
transactions
Payments
• Single
payment
• Multipl...
Package By Layer
Application Services
• Account
• Open new account
• OpenNewAccountUseCase
• ICreateAccountCommand
Domain ...
Package By Component
Account
• Application Services
• Open new account
• OpenNewAccountUseCase
• ICreateAccountCommand
• D...
Package By Feature
Account
• Open new account
• OpenNewAccountUseCase
• ICreateAccountDbCommand
• CreditCheckService
• IGe...
Change Request Comparison
Package by layer
 Must change code in multiple projects
Package by component
 Must change co...
Event Sourcing
ExecuteUseCase: _log.UseCase(useCaseInput) generates a stream of
executed use cases/events
A use case sho...
Replay Use Cases/Events
Stream of use cases/events can be replayed
 Test the system for errors
 Restore from failure
H...
Summary
Use Inversion of Control to write testable and loosely coupled code
Use Single Responsibility Principle to write...
The information contained in this presentation is proprietary.
© 2014 Capgemini. All rights reserved.
www.capgemini.com
Application Architecture
Application Architecture
Application Architecture
Application Architecture
Application Architecture
Application Architecture
Application Architecture
Upcoming SlideShare
Loading in...5
×

Application Architecture

799

Published on

Slides from my talk on application architecture and clean code.

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
799
On Slideshare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
34
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Application Architecture

  1. 1. Application Architecture 2014 Lars-Erik Kindblad Senior Consultant & Head Of Microsoft Community Of Practice
  2. 2. Feature Delivery For Most Software Projects Project Progress • Complex and messy code • Code and logic is duplicated • No common coding standard • No strict architecture • ++
  3. 3. Ideal Feature Delivery Project Progress
  4. 4. Agenda Testable code  Inversion of Control Maintainable code with less duplication  Single Responsibility Principle  Extract Method Principle  Execute Around Method Pattern Well structured code  Onion Architecture & N-Layered Architecture  Ways to group and structure code Reduce bugs  Event Sourcing & replaying events
  5. 5. Inversion Of Control Make code loosely coupled Make unit testing possible
  6. 6. Traditional Code
  7. 7. Inversion Of Control
  8. 8. Traditional code Main class UserCreator CreateUser DbCommand 1. Creates 2. Creates Inversion of control code Main class UserCreator CreateUser DbCommand Dependency 1. Creates 2. Creates with object from 1. Dependency
  9. 9. Dependency Injection - Constructor Injection
  10. 10. Dependency Injection - Interface Injection
  11. 11. Dependency Injection - Setter Injection
  12. 12. Static Service Locator
  13. 13. Injected Service Locator
  14. 14. Which Patterns To Use
  15. 15. Traditional Code
  16. 16. Dependency Injection - Constructor Injection
  17. 17. Dependency Injection - Interface Injection
  18. 18. Dependency Injection - Setter Injection
  19. 19. Static Service Locator
  20. 20. Injected Service Locator
  21. 21. When To Use Which Patterns
  22. 22. Always Use Dependency Injection – Constructor Injection ...except
  23. 23. Facade Classes
  24. 24. Dependency Injection
  25. 25. Service Locator
  26. 26. Loops
  27. 27. Dependency Injection
  28. 28. Service Locator
  29. 29. Base Classes
  30. 30. Dependency Injection
  31. 31. Service Locator
  32. 32. Unknown Types At Compile Time
  33. 33. Service Locator
  34. 34. Summary Constructor Injection Injected Service Locator Facade classes (WCF Services, MVC Controllers) X Loops X X Base classes X Unknown types at compile time X All other scenarios X
  35. 35. Inversion Of Control (IOC) Container A framework that can automatically create an instance of a given type with all the required dependencies Popular frameworks  Unity, Castle Windsor, Ninject, StructureMap etc. Manual approach Using an IOC container
  36. 36. Configuration Must register what types the container can resolve Types are registered with a life time manager  PerContainer – Container.Resolve<UserCreator> returns the same UserCreator instance every time (Singleton)  Transient – Container.Resolve<UserCreator> returns a new UserCreator instance every time  PerRequest – Container.Resolve<UserCreator> returns the same UserCreator instance within a web request Configuration can be done through  XML – Read from the .config file. Bad practice, too limiting  Code – Register all types through code • Auto registration – Automatically register types based on conventions e.g. all types in assembly x
  37. 37. Where To Plugin An IOC container should be created and initialized in the presentation layer or or above (DependencyResolution layer) Any other layer should NOT have a reference to the IOC container Presentation Domain Database, Web Service, Queue, SMTP server etc. Infrastructure Don’t reference container here Don’t reference container here Should reference and use container
  38. 38. Unity Example 1/3
  39. 39. Unity Example 2/3
  40. 40. Unity Example 3/3
  41. 41. Summary Use an IOC Container to create type instances when using inversion of control Only the presentation layer should know about the IOC Container Configuration: Prefer code over xml Use auto registration to reduce configuration code
  42. 42. Single Responsibility Principle Single Responsibility Principle = SRP 1 of the 5 SOLID principles ”A class or module should have one, and only one, reason to change”  A class should do one thing  A class should have only one responsibility Max 100-200 lines of code per class? The benefits  Easier to give the class a good name  Easier to read  Easier to maintain & extend  Easier to test
  43. 43. The God Object A God object is an object that knows too much or does too much The opposite of the SRP
  44. 44. Single Responsibility Objects
  45. 45. Current responsibilities: • Facade class • Input validation • Talks to a database • Sends e-mail
  46. 46. Refactored To SRP UserManager CreateUser GetUser DeleteUser
  47. 47. Refactored UserManager Responsibility • Facade class
  48. 48. Refactor GetUser & DeleteUser Responsibility • Return the user from the database Responsibility • Delete the user from the database
  49. 49. Refactored to CreateUser Responsibility • Input validation • Create the user in the database • Send confirmation e-mail
  50. 50. Future Refactoring Split into multiple classes when the code increases in size CreateUser CreateUserDbCommand SendEmailConfirmation
  51. 51. Summary A class following the single responsibility principle is a class that does only one thing and has only one reason to change The opposite of SRP is a God-object Benefits  Easy to give the class a good name  Less code per class means • Reduced complexity = less errors • Easier to maintain & extend • Easier to test Can use the Facade pattern if a special API is required
  52. 52. Code Duplication – Example #1 Duplicated code
  53. 53. Extract Method Principle - Refactored
  54. 54. Code Duplication – Example #2 Duplicated code
  55. 55. Execute Around Method Pattern - Refactored
  56. 56. Execute Around Method - Example #2
  57. 57. Domain Model Domain Services Presentation Application Services Infrastructure Frameworks and external endpoint integrations Onion Architecture  A layer can only depend on inner layers  Frameworks and infrastructure concerns are pushed to the outer layer  A change of framework will not affect the application core Application business rules = use cases Enterprise business rules Database, Web Service, Queue, SMTP server etc. Application Core
  58. 58. Onion Architecture Flattened Presentation Application Services Domain Services Database, Web Service, Queue, SMTP server etc. Domain Model Infrastructure
  59. 59. The Use Case – Open New Account Create new account in database and return account number Is personal number empty? Is the customer credit worthy? Return error No Yes Yes No
  60. 60. Dependency Resolution Domain Model Domain Services Presentation Application Services Infrastructure AccountController Database Onion Architecture – Open New Account Use Case • OpenNewAccountUseCase • ICreateAccountCommand CreateAccount- DbCommand • CreditCheckService • IGetTotalDebtForCustomerQuery Web service GetTotalDebtForCustomer- ServiceAgent ExecuteUseCase
  61. 61. Process Flow AccountController OpenNewAccountUseCase CreateAccountDbCommand CreditCheckService GetTotalDebtForCustomer- ServiceAgent ExecuteUseCase DependencyResolver Unity IOC Container Database Web service • Transaction management • Exception handling • Logging Insert/Update/Delete = *Command Read = *Query
  62. 62. Alternatives – 3-Layered Architecture Where are the use cases? Presentation Domain Services Domain Model Database, Web Service, Queue, SMTP server etc. Infrastructure
  63. 63. Alternatives – 4-Layered Architecture Must always go through domain layer – domain layer will get non-domain code All return types from Domain Services or Infrastructure must be declared in the Domain Model Presentation Application Services Domain Services Domain Model Database, Web Service, Queue, SMTP server etc. Infrastructure
  64. 64. Alternatives – 4-Layered Architecture – Non-Strict The application- and domain logic is tightly coupled to the infrastructure  Domain Centric vs Data Centric architecture Presentation Application Services Domain Services Domain Model Database, Web Service, Queue, SMTP server etc. Infrastructure
  65. 65. The Use Cases Open new account View accounts Latest transactions Single payment Multiple payments International payment View Executed payments View policies Change address Change payment limit
  66. 66. Group Into Components Account • Open new account • View accounts • Latest transactions Payments • Single payment • Multiple payments • International payment • View Executed payments Insurance • View policies Settings • Change address • Change payment limit
  67. 67. Package By Layer Application Services • Account • Open new account • OpenNewAccountUseCase • ICreateAccountCommand Domain Services • Account • Open new account • CreditCheckService • IGetTotalDebtForCustomerQuery ...
  68. 68. Package By Component Account • Application Services • Open new account • OpenNewAccountUseCase • ICreateAccountCommand • Domain Services • Open new account • CreditCheckService • IGetTotalDebtForCustomerQuery • ... Payments • Application Services • ...
  69. 69. Package By Feature Account • Open new account • OpenNewAccountUseCase • ICreateAccountDbCommand • CreditCheckService • IGetTotalDebtForCustomerQuery • ... Payments • ...
  70. 70. Change Request Comparison Package by layer  Must change code in multiple projects Package by component  Must change code in 1 project but multiple folders Package by feature  Must change code in 1 project, one folder
  71. 71. Event Sourcing ExecuteUseCase: _log.UseCase(useCaseInput) generates a stream of executed use cases/events A use case should either be a command or a query Serialized data Execution date Status OpenNewAccountInput 3. march Successful ChangeAddressInput 4. march Successful OpenNewAccountInput 7. march Successful ChangePaymentLimitInput 10. march Failed ChangePaymentLimitInput 11. march Successful
  72. 72. Replay Use Cases/Events Stream of use cases/events can be replayed  Test the system for errors  Restore from failure How to replay? Make an application that 1. Delete all the data in the database 2. Read first event in log 3. Resolve use case class from use case input 4. Execute use case 5. Read next event and goto 23.
  73. 73. Summary Use Inversion of Control to write testable and loosely coupled code Use Single Responsibility Principle to write small, easy to maintain classes Use Extract Method Principle & Execute Around Method pattern to reduce code duplication Use the Onion Architecture or N-Layer to get a fixed architecture Package by Layer-, Component- or Feature to get well organized code Log executed use cases and replay them before a new release to check for bugs
  74. 74. The information contained in this presentation is proprietary. © 2014 Capgemini. All rights reserved. www.capgemini.com
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×