Traditional programming is quite old (60+ years)
Object Oriented Programming is not so old, but old enough (35+ years)
We can say that OOP is able to satisfy our needs of Modern programming
Modern is not about modern programming principles and paradigms
Modern is about current scenarios in which our programming abilities have to be spent these days
Just 10 years ago (in 2K years) we were focusing on something else
Modern Programming for about modern programming challenges:
- Cloud
- Big Data
- Mobile and Devices
- Internet of Things
Principles
- Application Lifecycle Management
- Scrum
- Maintainable Code
Imperative Modeling
- Don’t tell what you want to do: just do it!
Responsibility Modeling
- Why are you coding? Which is the intention inside every line you write?
Functional Modeling
- Declare what you need! I’ll implement it!
Object Modeling
- Classes are the way to describe model into a domain
Contract Modeling
- Class is not just encapsulation. It’s also declaration of a contract
Interface Modeling
- Class should be implementation only. Interfaces are a better way to describe a contract
Three tier Modeling
- An Architectural model for an application
“Blueprints” Modeling
- Feel free to express yourself…or not? Please refer to some work done by experts!
“No more One” Modeling
- One model DOES NOT FITS for all. Multiple models are needed to single aspects of an application
2. Marco Parenzan
Formazione & Divulgazione con 1nn0va
Microsoft MVP 2014 for Microsoft Azure
Formazione & Progettazione con ITS Kennedy
Ricerca e Innovazione con Servizi Cgn
www.slideshare.net/marco.parenzan
marco [dot] parenzan [at] libero [dot] it
www.innovazionefvg.net
Developer e Architect in .NET e Web
Cloud Developer
Loves functional programming
Some videogames for fun
3. Modern Programming
Traditional programming is quite old (60+ years)
Object Oriented Programming is not so old, but old enough (35+ years)
We can say that OOP is able to satisfy our needs of Modern programming
Modern is not about modern programming principles and paradigms
So what?
4. Modern Programming
for Modern Scenarios
Modern is about current scenarios in which our programming abilities have to be spent
these days
Just 10 years ago (in 2K years) we were focusing on something else
Modern Programming for about modern programming challenges
Cloud
Big Data
Mobile and Devices
Internet of Things
5. Modern Scenarios: tenets
From Mauro Servienti presentation
http://www.slideshare.net/mauroservienti/in-the-brain-designing-distributed-scalable-and-
reliable-systems
“None of the following is true”
Network is reliable;
Latency is near to zero or irrelevant;
Bandwidth is unlimited;
Network is secure;
Topology doesn’t change;
Transport cost is irrelevant;
Network is homogeneous;
7. Foundations of Modern Web Development
Principles
Application Lifecycle Management
Scrum
Maintainable Code
Parameters
Development Cost (perceived, initially)
Development Cost (to long)
Complexity
Testability
Overall Quality
Scenarios
Mobile First
Cloud First
9. Readable code
Modern development is always «hurry» development
Documentation and analisys difficulty reflect exactly the code is written
Best code is readable, self documenting code
Best if a more approchable
Code have to go into a Version Control System, either Centralized (like SVN) or Distributed
(like GIT)
10. Maintainable/«S.O.L.I.D.» code
Code have to be written to be handled next after development
Best property is «minimal coupling»
Some code that changes does not affect other code that uses the code
S.O.L.I.D. is an acronym for basic principles for maintainable code
11. Testable code
Test is a «fake» environment that simulates execution of code in an equivalent-to-real
environment
Test must me exaustive (code-coverage): a set of different calls that allows to test
parameters conditions
Parameter conditions are function of conditions
The more the conditions, the more the combinations and test cases
12. Pattern based code
Patterns means writing code «similar» to which other coders write in the same situation
Pattern help recognize this situation
Situations help recognize which pattern is better to apply
13. Scalable code
Apps are a template for processes
Legacy applications where «single process» on a single machine
What if multiple processess run multiple single processes at the same time?
How multiple machines can be reached independently and app execution is always
consistent?
15. Code and Modeling
Modeling is the activity of translating some requirements, results of an analysis activity
Code is a way to model «intentions» with «responsibilities» through a programming
language
Modeling is the activity of undestanding and specificating “the real world”
Coding is the activity of representing the modeling activity in a software with a language
16. Cloud code
Cloud Computing is not a specific environment
CC encourages writing good code to improve Application Lifetime Management
CC require agile approach to coding because of an evolving context
17. C# code
C# is a statically typed, strongly typed language
That guarantees benefits in a modern development environment like Visual Studio
C# is a great language to write Domain-oriented code
C#, alone, does not guarantee a writing a good application, without some other
principles
19. The path through modeling [1]
Imperative Modeling
Don’t tell what you want to do: just do it!
Responsibility Modeling
Why are you coding? Which is the intention inside every line you write?
Functional Modeling
Declare what you need! I’ll implement it!
Object Modeling
Classes are the way to describe model into a domain
Contract Modeling
Class is not just encapsulation. It’s also declaration of a contract
20. The path through modeling [2]
Interface Modeling
Class should be implementation only. Interfaces are a better way to describe a contract
Three tier Modeling
An Architectural model for an application
“Blueprints” Modeling
Feel free to express yourself…or not? Please refer to some work done by experts!
“No more One” Modeling
One model DOES NOT FITS for all. Multiple models are needed to single aspects of an application
22. We start with a problem to solve…
…typically with a divide and conquer technics
In traditional programming, we figure out how to break the problem into smaller parts,
then each part into smaller parts still…with an emphasis on doing.
In the object-oriented approach we then try to figure out what objects the system has,
what their responsibility is, and how they interact
Alec Sharp, Sharp, “Smalltalk By Example”,
page 10, McGraw-Hill, 1997
23. Imperative Programming
http://en.wikipedia.org/wiki/Programming_paradigm
imperative programming is a programming paradigm that describes computation in terms of statements that
change a program state
No assumptions are done…
…where state is…
…who can change state…
…protect state…
Focus is on statements
Origin of algorithms
Evolution of Von Neumann model (not so different from Machine Language, Assembly model)
The notion of algorithm!
Express how to do…what?
You express the single lines of code without explaining the intention
24. How do you organize statements?
You organize statements through grouping blocks of statements
Creating distinct blocks of statements means encapsulation
Encapsulation is represented by giving this block a name
Name reflects intention of the block to the state
What is a «good» encapsulation?
Is a state that is used only from a single, encapsulated, block of code
26. Intention
An intention is a piece of code with a role (in your entire code)
Less roles (best: one!) better is the intention
So you need many intentions!
“Why have you wrote that code?”
“Which was your intention?”
27. Tell, don’t Ask
Procedural code gets information then makes decisions.
Object-oriented code tells objects to do things.
Alec Sharp, Sharp, “Smalltalk By Example”,
page 67, McGraw-Hill, 1997
Smalltalk, where objects born…
28. “Any intention has a
consequence”
Are you responsible about your intention?
30. Responsibility
The intention is a boundary of responsibility
Responsibility has many definitions. For example:
A responsibility is an obligation to perform a task or know information
http://en.wikipedia.org/wiki/Responsibility-driven_design#objects
31. Responsibility for what?
Program «calculate» a result
A result is a fact, but is not always «instantly» calculated
A result is the end of a «path» that goes through a «state» that changes as program go on
In math terms, sequence of values must «converge» to the result
Wrong manipulation of state (values) creates side effects and arrival to a wrong result
Responsibility is the guarantee of the intention of correct state management to arrive to
correct result
How do you describe the responsibility? Through code
32. It’s not your responsibility!
The problem is that, as the caller, you should not be making decisions based on the state
of the called object that result in you then changing the state of the object.
The logic you are implementing is probably the called object’s responsibility, not yours. For
you to make decisions outside the object violates its encapsulation.
Tell just “what you want to do”
Don’t ask something (state) so you can decide
35. Encapsulation
Encapsulation is assigning a name to an intention
A program in a (un)ordered set of intentions
More detailed is the name of the intentions, better is the result
Less detailed are intentions, more work is for you
36. How ENCAPSULATION is implemented in
code?
With Functions
With Classes and Objects
With Interfaces
37. Why Encapsulation
Give a Name («define a message») to an ability
From the implementer Point of View
Invoke a Name («send a message») to ask for an ability
From the consumer Point of View
Encapsulation has an important consequence
38. Give me some examples of
encapsulated intentions!
Good
CreateAnOrderForCustomer
CalculateTotalAmountToPay
GenerateSummaryReport
Bad
CreateAnOrderWithTotalForCustomerAnd
GenerateSummaryReport
CrOrdTotCustGenSumRep
40. Imperative vs. Declarative
Imperative==(you) ASK to DO (yourself)
And you DON’T SAY what you need
Declarative=(you) TELL to MAKE it DONE (by someone else)
You SAY what you need
You don’t know how it is done
41. Declarative Code
Describe what you want to obtain (the result)
Then there is the topic about (how to obtain)
It can be that tool (the language, the compiler) can do that work or you
The most common example of this is SQL
Functional Code: a declarative approach solved using functions
42. Functional
You express the intention on how state change (relation before-after)
You enforce this with invariants (values that doesn’t change)
44. Objects and Classes
Objects is a structure that encapsulates state and behavior that evolve that state
Class is a mechanism to declare the encapsulation of state and and behavior
Class-based languages implements these principles with many options on principle
enforcement (strong, wake)
Note. There are also other paradigms to define objects (ex. Prototyping, as for Javascript)
45. Encapsulation in OOP
Encapsulation, inheritance, and polymorphism are the three pillars of object-oriented
programming.
Encapsulation is the packing of data and functions into a single component.
The features of encapsulation are supported using classes. It allows selective hiding of
properties and methods in a class by building an impenetrable wall to protect the code
from accidental corruption.
In programming languages, encapsulation is used to refer to one of two related but
distinct notions, and sometimes to the combination thereof:
A language mechanism for restricting access to some of the object's components.
A language construct that facilitates the bundling of data with the methods (or other functions)
operating on that data.
47. Type as a Contract
Class Declaration is useful to compiler during coding activity
Compiler ensure classes respecting Contract implementation
Contract is expressed in terms of Interface and Class members
48. Class Model=Contract
Every class express completly a contract
What is not expressed cannot be in the contract
Every class implements a contract. Possibilities:
completly
partially
extendibly
nothing
49. Polymorphysm
Contract implementation is not limited to ONE IMPLEMENETATION
Contract can have multiple implementations (or POLY MORPHS)
Many implementantions are different to give different performances to the same contract
Polymorphism is implemented via inheritance
51. Public and private definitions
Public class is a shared contract
Private class is an reserved implementation
A private implementation assolve at the end to a public contract
A contract cannot be private!
Not shared
It’s unuseful an object that doesn’t have a public function
A public implementation is a loose of encapsulation and responsibility
52. Completely implement a contract
A class that completly implements its contract can be instantiated
Side effect:
Languages allows a completly defined class not bein instantiated
No factory MethodsBah!
Factory MethodsOK!
53. Partially implement a contract
Class must be inherited
Some implementation details are missing
Contract detail are not missing
…to complete its implementation
Many “combination” of details can generate many implementations
Opportunity!
Side effect
Inheritance can extend contract, not change!
54. Extendibly implement a contract
(partial) implementation of the contract can be extended
Extension is done through override
Side effect
Implementation can change the behavior, not extend
Is a responsibility of the implementer
Language cannot ensure that
You are building a taxonomy
55. Polymorphysm implemented via
Inheritance
Inheritance is not functional to code reuse
There are many other ways to reuse code
Inheritance is functional to Polymorphysm
Single inheritance, not multiple (only C++ has)
“..is a…” relation
Being
No ambiguities
56. Inheritance is implementation hiding
«Less (you know) is better»
X is a class that inherits from A
Inheritance says:
X «derives from» A
X «is» A
X is able to do everything A is able to do
X can do the work in place where A is requested
57. Inheritance is reuse
«Inheritance is not functional to code reuse «
X and Y are two classes that inherits from A
X and Y can (not HAVE TO) extend contract
X and Y HAVE TO do work in place where A is requested, but…
…if X and Y are use independently you don’t need inheritance!
59. Class not implement a contract
Extreme condition for a class
All members are abstract
Code-based inheritance for classes with all abstract members is wrong
At least, not so useful or a lost of opportunity
Use interfaces
Is an encapsulation of some method in a responsibility
Interface is declaration of some kind of responsibility
Interface implementation can be implicit or explicit
Side effect
Multiple interfaces can violate SOLID principles
60. Inheritance, Interaces, Reflection
and language
Inheritance is done via reflection
Is the invariant part of the state of an object
Implemented through v-tables
In C#, is operator have to be used
Is operator is statically typed, strongly typed
Reflection is runtime object introspection
Reflection “engine” is loosely typed, dynamically typed
Flexible…
…but not maintainable…
62. n-Tier
A tier is a responsibility container
Tiers are «stacked»
A tier communicate with two layers, at most!
Tier-2
Tier-1
Tier-n
…
63. n-Tier
A tier is a responsibility container
Tiers are «stacked»
A tier communicate with two layers, at most!
Ok, not always true
Tier-2
Tier-1
Tier-n
…
64. Three Tier
Three is the most famous standard
n-Tier configuration
How do tiers communicate each other?
Define responsibility between layers
Have responsibility for «lower» layer
Consume responsibility by «top» layer
Business Logic
Data Access
PresentationData
65. Interfaces == Contract
Contract: agreement between parts
Define:
How are you talking (Interface)
Interface=Sentence
What are you talking about (Model)
Model==Words
Contract==Interfaces
Model
66. Contracts and Development Teams
«Three» teams can develop independently, if they agree
on Contracts
Contract DA/BL
Contract BL/P
67. Interfaces and Layers
Layers communicate each other via
contracts/interfaces
Business Logic
Data Access
Presentation
Contract DA/BL
Contract BL/P
69. Database (First)
Database is analysis
Database is «contract»
We’ll speak about with #DDD
Up to now, this is a common assumption
https://speakerdeck.com/manuelscapolan/the-role-of-the-database-in-a-domain-driven-design-world
70. Scaffolding
http://en.wikipedia.org/wiki/Scaffold_(programming)
…because DB tells you everything
… generate the final code that the application can use
to create, read, update and delete database entries…
It creates a model (an abstraction for table) and a Data
Access (an abstraction for Database)
Data Session
Model
71. Database First Three Tier
When we put togeter Three Tier and Scaffolding, we
tipically forget (or confuse) Model with Contract
Model is part of the Contract
Data Access is not a contract, but only operations on
data
We can only accept, not agreeBusiness Logic
Data Access
Presentation
Model
72. MVC
MVC Database First Three Tier
Modern Web Presentation is Model View
Controller
Controller is coordination in Presentation
View is Output Template
Model is…the same DB
model…AAARRRGGGHHH!!!!
This is a common mistake
Not the rule of MVC
There is a problem with terms (Model,
VIEWmodel, Data Transfer Objects, etc…)
Model because of «modeling» activity, not
model from DB!
Business Logic
Data Access
Controller
View
Model
73. MVC
Scaffolded MVC
Database First Three Tier
Put all togheter
+ Database First
+ Scaffolding
+ Three Tier
+ MVC
+ (-Business Logic)
= Real bomb!
Data Session
Controller
View
Business Logic
Model
75. Scaffolding Scenario
“Build model from metadata”
You model classes from Database
You model classes for storage (Entity)
Classes as Aggregate of data by ownership
You decide queries during development
Entity is atomic
All or nothing
76. Mistake #1: No encapsulation
No responsibility
Pay attention on code you change.
Your change can have effectes on others…
Manteinance penalty
Cost
Bugs
77. Mistake #2: No scalability
OK it can scale...
…but are you free to choose?
(RDBMS) Database First is a costraint
Vertical scalability as the only opportunity
Horizontal scalability is no more an opportunity
Performance penalties
Speed
Money
78. Mistake #3: Modeling, not Model!
Model in MVC is the result of a modeling activity, not a model from OR/M!
There are many models types
View Models
Domain Models
Anemic Models
…
DB is not a contract
79. Mistake #4: one model does not fits for all
Foremost, Model is «stretched» as contract between all tiers
Because it’s DATABASE model, not BUSINESS model
One model for DYNAMIC queries
Because you don’t know which queries you need
No queries in analisys
82. Blueprints for objects: patterns
How do you use all these things?
How do you build up a class?
I’m the first that ever build an object?
83. Experience from many, not just one
Many have collected experiences
Experiences are collected as patterns
Patterns grouped by usage
Design Patterns
(Gand of our, Gamma et al)
http://en.wikipedia.org/wiki/Design_Patterns
Patterns of Enterprise Application Architecture
(Martin Fowler)
http://martinfowler.com/eaaCatalog/index.html
Object Oriented Design
http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfO
od
Cloud Computing Patterns
http://www.cloudcomputingpatterns.org/
Domain Driven Design
http://en.wikipedia.org/wiki/Domain-driven_design
84. Experience from many
dogmas from no one
All patterns are effective experience…
…for most of the “standard” situations!
Every situation have to be verified because many parameters can influence how to
choose
Performances
Correctness
86. Presentation models
“Create/Read/Update/Delete model”
You model classes from Scenarios
You model classes for view (ViewModel)
You can decide queries during development
Mapping is a valuable costing
ViewModel is atomic
ViewModel map to some part of an entity
87. ViewModel
Is a model of an entity optimized for UI
No Database-like references
An entity object is not suitable for universal usage
No localization
Data already decoded
Data already loaded (if good to)
A ViewModel is typically an “pure” “language” object
Minimize (down to zero) needs of getting other data from other sources
88. Queries in analysis
Define ViewModels in analysis
All data required are in analysis
You identify queries needed to map data from/to database
You start identifying tests
89. Pro & Cons….Cons?
In a ViewModel you have “parts” of a Database model
You can have MANY viewModels that corresponds to a single Database Model
Is this a cons? No
Cons
Many, not one
Slow…more to code
Pro
More testable
Fast…code at runtime
91. Decide what you need to do
Don’t make implicit choices
Don’t choose for others
Pretend to know what they need to do
92. Decide what you want to do then
It’s your intention
You decide an action to do
That’s action is composing a command
93. Send you command
Command object is a object that assert an intention to an action
All values assigned to properties specify parameters of the intention of the command
Typically, this kind of objects are flat (not complex)
Typically this object have no particular dependencies
Don’t expect immediate execution
Ccommand can be queued
94. Data Transfer Object - DTO
An object that carries data between processes in order to reduce the number of method
calls (http://martinfowler.com/eaaCatalog/dataTransferObject.html)
An aggregate of information
A mono-directional object optimized for data presentation
Typically is a result of mapping of a generic query from a datasource
95. Recap CQRS Scenario
“Command/Query Responsibility Segregation”
You model classes from requests and responses
You model classes for actions (Commands) and queries
Classes as aggregates of parameters (Commands) and aggregates of values (Data
Transfer Objects)
You need to decide queries during development, because Model can be huge
Command is atomic, DTO is atomic
ViewModel work to
96. CQRS defined
CQRS stands for Command Query
Responsibility Segregation. It's a pattern
that I first heard described by Greg Young
At its heart is a simple notion that you can
use a different model to update
information than the model you use to
read information
This simple notion leads to some profound
consequences for the design of
information systems.
From Martin Fowler
http://martinfowler.com/bliki/CQRS.html
97. Comparing Application Scenarios
Scaffolding View Models CQRS
Development Time
(perceived, initially)
Low Average High
Development Cost
(to long)
High Average Average
Complexity High Average Low
Testability Low Average High
Overall Quality Low Average High
98. Model costs
0
100
200
300
400
500
600
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Scaffolding
ViewModels
CRUD
CQRS cost is substantially
costant through the
implementation of the entire
loop