SlideShare a Scribd company logo
1 of 86
Download to read offline
EnterpriseTic-Tac-Toe
@ScottWlaschin
fsharpforfunandprofit.com
In which I ridiculously over-engineer a simple game to
create a real-world "enterprise-ready" application.
Proper name is "Noughts and Crosses" btw
EnterpriseTic-Tac-Toe
What you need for “Enterprise”?
• Siloed organization Specialized teams
• ArchitectureTeam
• Project ManagementTeam
• Front End DevelopmentTeam
• Back End DevelopmentTeam
• OperationsTeam
• SecurityTeam
• Compliance and AuditingTeam Can we make them
all happy?
What you need for “Enterprise”?
• Separation of concerns so that specialist teams can work
on different parts of the code at the same time.
• A documented API so that the different teams can work
effectively in parallel.
• A security model to prevent unauthorized actions from
occurring.
• Well-documented design so that the architect can ensure
that the implementation matches the UML diagrams.
• Auditing and logging to ensure that the system is
compliant.
• Scalability to ensure that the system is ready for the
challenges of rapid customer acquisition.
Project Manager: "We need
separation of concerns because
the front-end team and back-
end team hate each other and
refuse to work in the same
room."
Separation of concerns so that specialist teams
can work on different parts of the code at the same
time.
Front-end team: "We need a
documented API so that
those dummies building
the back-end won't keep
breaking our code on
every commit."
A documented API so that the different teams can
work effectively in parallel.
Back-end team: "We need a
security model because those
idiots building the front-end
will always find a way to do
something stupid unless we
constrain them."
A security model to prevent unauthorized actions
from occurring.
Maintenance team: "We
need well-documented
design because we're fed
up of having to reverse
engineer the hacked-up
spaghetti being thrown at
us."
Well-documented design so that the architect
can ensure that the implementation matches the
UML diagrams.
Testers and Operations: "We
need auditing and logging so
that we can see what the effing
system is doing inside."
Auditing and logging to ensure that the system is
compliant.
Everyone: "We don't really need scalability at all, but
the CTO wants to us to be buzzword compliant."
Scalability to ensure that the system is ready for
the challenges of rapid customer acquisition.
I’m gonna use F#, so here’s
all the F# you need
type Pair = int * int "*" means a pair
type Payment =
| Cash
| Card of CardNumber
"|" means a choice
typeThing = { name:string }
"{" means a record
type AFunction =
string ->
int
A Function
42
“Deep
Thought”
A Function
type AFunction =
string ->
int * bool
Input is a string
Output is a pair
A Function
type AFunction =
bool * string ->
int
Input is a pair
Output is a int
TYPE DRIVEN DESIGN
Growing functional software,
guided by types
Type driven design
• Design with types only
– no implementation code.
• Every use-case/scenario corresponds to a
function type
– one input and one output
• Work mostly top-down and outside-in
– Occasionally bottom up as well.
• We ignore the UI for now.
Tic-Tac-Toe Scenarios
• Initialize a game
• A move by Player X
• A move by Player O
type StartGame =
unit ->
GameState
StartGame
Game Statenothing
OtherStuff
Player X
Moves
type PlayerXMove =
GameState * SomeOtherStuff ->
GameState
GameState
(before) GameState
(after)
Before After
Loop
OtherStuff
Player O
Moves
type PlayerOMove =
GameState * SomeOtherStuff ->
GameState
GameState
(before) GameState
(after)
 both functions look exactly
the same and could be easily
substituted for each other.
UserAction
Any
Kind of
Move
type UserAction =
| MoveLeft
| MoveRight
| Jump
| Fire
GameState
(before) GameState
(after)
Generic approach
UserAction
Any
Kind of
Move
type UserAction =
| PlayerXMove of SomeStuff
| PlayerOMove of SomeStuff
GameState
(before) GameState
(after)
Generic approach applied to this game
But we have TWO players so should have two functions....
type PlayerXMove =
GameState * PlayerX's Stuff ->
GameState
type PlayerOMove =
GameState * PlayerO's Stuff ->
GameState
Each type is different and the
compiler won’t let them be mixed up!
What is the other Stuff?
For some domains there might be a LOT of stuff...
But in Tic-Tac-Toe, it's just the location on the grid where
the player makes their mark.
type HorizPosition =
Left | Middle | Right
type VertPosition =
Top | Center | Bottom
type CellPosition =
HorizPosition * VertPosition
type PlayerXMove =
GameState * CellPosition ->
GameState
type PlayerOMove =
GameState * CellPosition ->
GameState
Same again 
type PlayerXMove =
GameState * PlayerXPos ->
GameState
type PlayerOMove =
GameState * PlayerOPos ->
GameState
type PlayerXPos =
PlayerXPos of CellPosition
type PlayerOPos =
PlayerOPos of CellPosition
Different
functions
Different
positions
What is the GameState?
type GameState = { cells : Cell list }
type CellState =
| X
| O
| Empty
type Cell = {
pos : CellPosition
state : CellState }
What is the GameState?
type GameState = { cells : Cell list }
type Player = PlayerX | PlayerO
type CellState =
| Played of Player
| Empty
type Cell = {
pos : CellPosition
state : CellState }
Refactor!
What is the Output?
What does the UI need to know?
The UI should not have to "think" -- it should
just follow instructions.
What is the Output?
1) Pass the entire game state to the UI?
But the GameState should be opaque...
What is the Output?
1) Pass the entire game state to the UI?
2) Make the UI's life easier by explicitly returning
the cells that changed with each move
type PlayerXMove =
GameState * PlayerXPos ->
GameState * ChangedCells
Too much trouble in this case
What is the Output?
1) Pass the entire game state to the UI?
2) Make the UI's life easier by explicitly returning
the cells that changed with each move
3)The UI keeps track itself but can ask the server
if it ever gets out of sync
type GetCells = GameState -> Cell list
Time for a walkthrough...
Start game
Player X moves
Player O moves
Player X moves
Player O moves
Player X moves
Player X wins!
Time for a walkthrough...
Start game
Player X moves
Player O moves
Player X moves
Player O moves
Player X moves
Player X wins!
Player O moves
Player X moves
Player O moves
Player X moves
Player O moves
Player X moves
Player O moves
Player X moves
Did I mention that
the UI was stupid?
When does the game stop?
type GameStatus =
| InProcess
| Won of Player
| Tie
type PlayerXMove =
GameState * PlayerXPos ->
GameState * GameStatus
How does the UI know?
Returned with the
GameState
Review
What kind of errors can happen?
• Could the UI create an invalid GameState?
– No. We’re going to keep the internals of the game state hidden from
the UI.
• Could the UI pass in an invalid CellPosition?
– No. The horizontal/vertical parts of CellPosition are restricted.
• Could the UI pass in a valid CellPosition but at the wrong time?
– Yes -- that is totally possible.
• Could the UI allow player X to play twice in a row?
– Again, yes. Nothing in our design prevents this.
• What about when the game has ended but the stupid UI forgets
to check the GameStatus and doesn't notice.
– The game logic needs to not accept moves after the end!





Returning the available moves
type ValidMovesForPlayerX = PlayerXPos list
type ValidMovesForPlayerO = PlayerOPos list
type PlayerXMove =
GameState * PlayerXPos ->
GameState * GameStatus * ValidMovesForPlayerO
type PlayerOMove =
GameState * PlayerOPos ->
GameState * GameStatus * ValidMovesForPlayerX
Now returned after
each move
What kind of errors can happen?
• Could the UI pass in a valid CellPosition but at the wrong time?
– No, it is not in the list of allowed moves.
• Could the UI allow player X to play twice in a row?
– No, the returned list only has moves for Player O
• What about when the game has ended but the stupid UI forgets
to check the GameStatus and doesn't notice.
– The list of moves is empty when the game is over


type PlayerXMove =
GameState * PlayerXPos ->
GameState * GameStatus * ValidMovesForPlayerO
type PlayerOMove =
GameState * PlayerOPos ->
GameState * GameStatus * ValidMovesForPlayerX

Some refactoring (before)
type GameStatus =
| InProcess
| Won of Player
| Tie
type PlayerXMove =
GameState * PlayerXPos ->
GameState * GameStatus * ValidMovesForPlayerO
Merge into
one type
Some refactoring (after)
type MoveResult =
| PlayerXToMove of GameState * ValidMovesForPlayerX
| PlayerOToMove of GameState * ValidMovesForPlayerO
| GameWon of GameState * Player
| GameTied of GameState
type PlayerXMove =
GameState * PlayerXPos -> MoveResult
type PlayerOMove =
GameState * PlayerOPos -> MoveResult
Time for a demo!
Hiding implementations with
Parametric Polymorphism
Hiding implementations with
Parametric Polymorphism
Enforcing encapsulation
• Decouple the "interface" from the
"implementation".
• Shared data structures that are used by both
the UI and the game engine.
(CellState, MoveResult, PlayerXPos, etc.)
• Private data structures that should only be
accessed by the game engine (e,g. GameState)
Enforcing encapsulation
• OO approaches:
– Represent GameState with an abstract base class
– Represent GameState with an interface
– Make constructor private
Enforcing encapsulation
• FP approach:
– Make the UI use a generic GameState
– GameState can stay public
– All access to GameState internals is via functions
• These functions “injected” into the UI
With List<T>, you can work with the list in many ways, but you
cannot know what the T is, and you can never accidentally write
code that assumes that T is an int or a string or a bool.
This "hidden-ness" is not changed even when T is a public type.
With a generic GameState
type PlayerXMove<'GameState> =
'GameState * PlayerXPos ->
'GameState * MoveResult
type PlayerOMove<'GameState> =
'GameState * PlayerOPos ->
'GameState * MoveResult
The UI is injected with these functions but
doesn’t know what the GameState *really* is.
Logging
move
We want to log the input
and output. But how?
Logging
move
Logging
log
Step 1: Create a log function
move
Logging
log
Step 2: glue all the functions
together using composition
log
move
Logging
log
Step 2: glue all the functions
together using composition
log
move
Logging
log
Step 3: use the new function in
place of old function
log
There's no need for a "decorator pattern"
in FP - it's just regular composition
Demo of logging
Client-server communication
How do you send domain
objects on the wire?
JSON over HTTP?
Enterprise Rating: C-

What communication method should we use?
XML & SOAP?
Enterprise Rating: A

What communication method should we use?
Enterprise Service Bus!
Enterprise Rating: A++

What communication method should we use?
Sending objects on the wire
type MoveResultDTO = {
moveResultType : string // e.g. "PlayerXToMove"
gameStateToken : string
// only applicable in some cases
availableMoves : int list
}
type MoveResult =
| PlayerXToMove of GameState * ValidMovesForPlayerX
| PlayerOToMove of GameState * ValidMovesForPlayerO
| GameWon of GameState * Player
| GameTied of GameState
Not serialization friendly
JSON/XML friendly
Demo of problems
Stupid people Evil people
What’s the difference? 
POLA &
Capability Based Security
Evolution of a configuration API
Say that the UI needs to set a
configuration option
(e.g. DontShowThisMessageAgain)
How can we stop a malicious caller doing bad things?
Attempt 1
Give the caller the configuration file name
interface IConfiguration
{
string GetConfigFilename();
}
var filename = config.GetConfigFilename();
// open file
// write new config
// close file
API
Caller
 A malicious caller has the
ability to write to any file on
the filesystem
Attempt 2
Give the caller aTextWriter
interface IConfiguration
{
TextWriter GetConfigWriter();
}
var writer = config.GetConfigWriter();
// write new config
API
Caller
 A malicious caller can
corrupt the config file
Attempt 3
Give the caller a key/value interface
interface IConfiguration
{
void SetConfig(string key, string value);
}
config.SetConfig(
"DontShowThisMessageAgain", "True");
API
Caller
 A malicious caller can set
the value to a non-boolean
Attempt 4
Give the caller a domain-centric interface
enum MessageFlag {
ShowThisMessageAgain,
DontShowThisMessageAgain
}
interface IConfiguration
{
void SetMessageFlag(MessageFlag value);
void SetConnectionString(ConnectionString value);
void SetBackgroundColor(Color value);
}
API
 What's to stop a malicious caller
changing the connection string when they
were only supposed to set the flag?
Attempt 5
Give the caller only the interface they need
interface IWarningMessageConfiguration
{
void SetMessageFlag(MessageFlag value);
}
API
 The caller can *only* do the thing we
allow them to do.
Good security implies
good design
Good security is good design
• Filename => limit ourselves to file-based config files.
– ATextWriter makes the design is more mockable
• TextWriter => exposing a specific storage format
– A generic KeyValue store make implementation choices
more flexible.
• KeyValue store using strings means possible bugs
– Need to write validation and tests for that 
– Statically typed interface means no corruption checking
code. 
• An interface with too many methods means no ISP
– Reduce the number of available methods to one!
Capability based design
• In a cap-based design, the caller can only do
exactly one thing -- a "capability".
• In this example, the caller has a capability to
set the message flag, and that's all.
Stops malicious AND stupid callers doing bad things!
Attempt 5
A one method interface is a function
interface IWarningMessageConfiguration
{
void SetMessageFlag(MessageFlag value);
}
OO API
Action<MessageFlag> messageFlagCapability
Functional API
Capability Based Security and
Tic-Tac-Toe
Switching to cap-basedTic-Tac-Toe
type MoveResult =
| PlayerXToMove of
DisplayInfo * NextMoveInfo list
| PlayerOToMove of
DisplayInfo * NextMoveInfo list
| GameWon of DisplayInfo * Player
| GameTied of DisplayInfo
type NextMoveInfo = {
posToPlay : CellPosition
capability : MoveCapability }
This is a function
This is for UI
information only.
The position is
"baked" into the
capability
Cap-based Demo
HATEOAS
Hypermedia As The Engine
Of Application State
“A REST client needs no prior knowledge
about how to interact with any particular
application or server beyond a generic
understanding of hypermedia.”
RESTful done right
How NOT to do HATEOAS
POST /customers/
GET /customer/42
If you know the API
you’re doing it wrong
How to do HATEOAS
POST /81f2300b618137d21d /
GET /da3f93e69b98
You can only know what URIs
to use by parsing the page
HATEOAS Demo
Some Benefits of HATEOAS
• The server owns the API model and can
change it without breaking any clients
– E.g. Change links to point to CDN
– E.g. Versioning
• Simple client logic
• Explorable API
Review: How “enterprise” are we?
• Separation of concerns
• A documented API
• Well-documented design
type MoveResult =
| PlayerXToMove of
GameState * ValidMovesForPlayerX
| PlayerOToMove of
GameState * ValidMovesForPlayerO
| GameWon of GameState * Player
| GameTied of GameState



Review: How “enterprise” are we?
• A security model
• Auditing and logging
• Scalability
You can just waffle here:
"immutable" blah blah blah
"no side effects" blah blah blah
Your CTO will be impressed.



Thanks!
@ScottWlaschin
fsharpforfunandprofit.com/ettt
fsharpworks.com
Contact me
Slides and video here
Let us know if you
need help with F#

More Related Content

What's hot

API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8José Paumard
 
[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?NAVER D2
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented ProgrammingScott Wlaschin
 
Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Scott Wlaschin
 
The lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of testsThe lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of testsScott Wlaschin
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptForziatech
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureJosé Paumard
 
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Scott Wlaschin
 
Thirteen ways of looking at a turtle
Thirteen ways of looking at a turtleThirteen ways of looking at a turtle
Thirteen ways of looking at a turtleScott Wlaschin
 
Data Persistence in Android with Room Library
Data Persistence in Android with Room LibraryData Persistence in Android with Room Library
Data Persistence in Android with Room LibraryReinvently
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySqlDhyey Dattani
 
Game Development With Python and Pygame
Game Development With Python and PygameGame Development With Python and Pygame
Game Development With Python and PygameChariza Pladin
 
Intrinsic Methods in HotSpot VM
Intrinsic Methods in HotSpot VMIntrinsic Methods in HotSpot VM
Intrinsic Methods in HotSpot VMKris Mok
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js ExpressEyal Vardi
 
The Power Of Composition (DotNext 2019)
The Power Of Composition (DotNext 2019)The Power Of Composition (DotNext 2019)
The Power Of Composition (DotNext 2019)Scott Wlaschin
 

What's hot (20)

API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8
 
NestJS
NestJSNestJS
NestJS
 
[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented Programming
 
Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)
 
The lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of testsThe lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of tests
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
 
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
 
Thirteen ways of looking at a turtle
Thirteen ways of looking at a turtleThirteen ways of looking at a turtle
Thirteen ways of looking at a turtle
 
PHP Basic & Variables
PHP Basic & VariablesPHP Basic & Variables
PHP Basic & Variables
 
Data Persistence in Android with Room Library
Data Persistence in Android with Room LibraryData Persistence in Android with Room Library
Data Persistence in Android with Room Library
 
Express js
Express jsExpress js
Express js
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Python programming : Standard Input and Output
Python programming : Standard Input and OutputPython programming : Standard Input and Output
Python programming : Standard Input and Output
 
Game Development With Python and Pygame
Game Development With Python and PygameGame Development With Python and Pygame
Game Development With Python and Pygame
 
Intrinsic Methods in HotSpot VM
Intrinsic Methods in HotSpot VMIntrinsic Methods in HotSpot VM
Intrinsic Methods in HotSpot VM
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
The Power Of Composition (DotNext 2019)
The Power Of Composition (DotNext 2019)The Power Of Composition (DotNext 2019)
The Power Of Composition (DotNext 2019)
 

Similar to Enterprise Tic-Tac-Toe

Unreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal EditorUnreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal EditorNick Pruehs
 
Unreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game FrameworkUnreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game FrameworkNick Pruehs
 
Snake game implementation in c
Snake game implementation in cSnake game implementation in c
Snake game implementation in cUpendra Sengar
 
Silverlight as a Gaming Platform
Silverlight as a Gaming PlatformSilverlight as a Gaming Platform
Silverlight as a Gaming Platformgoodfriday
 
Sephy engine development document
Sephy engine development documentSephy engine development document
Sephy engine development documentJaejun Kim
 
Unity3d scripting tutorial
Unity3d scripting tutorialUnity3d scripting tutorial
Unity3d scripting tutorialhungnttg
 
98 374 Lesson 06-slides
98 374 Lesson 06-slides98 374 Lesson 06-slides
98 374 Lesson 06-slidesTracie King
 
Android application - Tic Tac Toe
Android application - Tic Tac ToeAndroid application - Tic Tac Toe
Android application - Tic Tac ToeSarthak Srivastava
 
Hi there I am having difficulty in finalizing my Tetris game , below.pdf
Hi there I am having difficulty in finalizing my Tetris game , below.pdfHi there I am having difficulty in finalizing my Tetris game , below.pdf
Hi there I am having difficulty in finalizing my Tetris game , below.pdffonecomp
 
Initial design (Game Architecture)
Initial design (Game Architecture)Initial design (Game Architecture)
Initial design (Game Architecture)Rajkumar Pawar
 
East Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...
East Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...East Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...
East Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...Gerke Max Preussner
 
[CB21] MUSHIKAGO: IT and OT Automation Penetration testing Tool Using Game AI...
[CB21] MUSHIKAGO: IT and OT Automation Penetration testing Tool Using Game AI...[CB21] MUSHIKAGO: IT and OT Automation Penetration testing Tool Using Game AI...
[CB21] MUSHIKAGO: IT and OT Automation Penetration testing Tool Using Game AI...CODE BLUE
 
West Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...
West Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...West Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...
West Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...Gerke Max Preussner
 
Tic tac toe c++ programing
Tic tac toe c++ programingTic tac toe c++ programing
Tic tac toe c++ programingKrishna Agarwal
 
Rapid prototyping with ScriptableObjects
Rapid prototyping with ScriptableObjectsRapid prototyping with ScriptableObjects
Rapid prototyping with ScriptableObjectsGiorgio Pomettini
 
速度——敏捷开发的丹田之气(2011敏捷中国大会)
速度——敏捷开发的丹田之气(2011敏捷中国大会)速度——敏捷开发的丹田之气(2011敏捷中国大会)
速度——敏捷开发的丹田之气(2011敏捷中国大会)Yi Xu
 
Ottawa unity user_group_feb13_2015
Ottawa unity user_group_feb13_2015Ottawa unity user_group_feb13_2015
Ottawa unity user_group_feb13_2015Karman Interactive
 

Similar to Enterprise Tic-Tac-Toe (20)

Unreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal EditorUnreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal Editor
 
Unreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game FrameworkUnreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game Framework
 
Snake game implementation in c
Snake game implementation in cSnake game implementation in c
Snake game implementation in c
 
Silverlight as a Gaming Platform
Silverlight as a Gaming PlatformSilverlight as a Gaming Platform
Silverlight as a Gaming Platform
 
Sephy engine development document
Sephy engine development documentSephy engine development document
Sephy engine development document
 
Unity3d scripting tutorial
Unity3d scripting tutorialUnity3d scripting tutorial
Unity3d scripting tutorial
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
 
98 374 Lesson 06-slides
98 374 Lesson 06-slides98 374 Lesson 06-slides
98 374 Lesson 06-slides
 
Android application - Tic Tac Toe
Android application - Tic Tac ToeAndroid application - Tic Tac Toe
Android application - Tic Tac Toe
 
Hi there I am having difficulty in finalizing my Tetris game , below.pdf
Hi there I am having difficulty in finalizing my Tetris game , below.pdfHi there I am having difficulty in finalizing my Tetris game , below.pdf
Hi there I am having difficulty in finalizing my Tetris game , below.pdf
 
Initial design (Game Architecture)
Initial design (Game Architecture)Initial design (Game Architecture)
Initial design (Game Architecture)
 
14a-gui.ppt
14a-gui.ppt14a-gui.ppt
14a-gui.ppt
 
East Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...
East Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...East Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...
East Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...
 
[CB21] MUSHIKAGO: IT and OT Automation Penetration testing Tool Using Game AI...
[CB21] MUSHIKAGO: IT and OT Automation Penetration testing Tool Using Game AI...[CB21] MUSHIKAGO: IT and OT Automation Penetration testing Tool Using Game AI...
[CB21] MUSHIKAGO: IT and OT Automation Penetration testing Tool Using Game AI...
 
West Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...
West Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...West Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...
West Coast DevCon 2014: Game Programming in UE4 - Game Framework & Sample Pro...
 
Tic tac toe c++ programing
Tic tac toe c++ programingTic tac toe c++ programing
Tic tac toe c++ programing
 
Rapid prototyping with ScriptableObjects
Rapid prototyping with ScriptableObjectsRapid prototyping with ScriptableObjects
Rapid prototyping with ScriptableObjects
 
InfectNet Technical
InfectNet TechnicalInfectNet Technical
InfectNet Technical
 
速度——敏捷开发的丹田之气(2011敏捷中国大会)
速度——敏捷开发的丹田之气(2011敏捷中国大会)速度——敏捷开发的丹田之气(2011敏捷中国大会)
速度——敏捷开发的丹田之气(2011敏捷中国大会)
 
Ottawa unity user_group_feb13_2015
Ottawa unity user_group_feb13_2015Ottawa unity user_group_feb13_2015
Ottawa unity user_group_feb13_2015
 

More from Scott Wlaschin

Domain Modeling Made Functional (DevTernity 2022)
Domain Modeling Made Functional (DevTernity 2022)Domain Modeling Made Functional (DevTernity 2022)
Domain Modeling Made Functional (DevTernity 2022)Scott Wlaschin
 
Building confidence in concurrent code with a model checker: TLA+ for program...
Building confidence in concurrent code with a model checker: TLA+ for program...Building confidence in concurrent code with a model checker: TLA+ for program...
Building confidence in concurrent code with a model checker: TLA+ for program...Scott Wlaschin
 
Reinventing the Transaction Script (NDC London 2020)
Reinventing the Transaction Script (NDC London 2020)Reinventing the Transaction Script (NDC London 2020)
Reinventing the Transaction Script (NDC London 2020)Scott Wlaschin
 
The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)Scott Wlaschin
 
Domain Modeling Made Functional (KanDDDinsky 2019)
Domain Modeling Made Functional (KanDDDinsky 2019)Domain Modeling Made Functional (KanDDDinsky 2019)
Domain Modeling Made Functional (KanDDDinsky 2019)Scott Wlaschin
 
Four Languages From Forty Years Ago (NewCrafts 2019)
Four Languages From Forty Years Ago (NewCrafts 2019)Four Languages From Forty Years Ago (NewCrafts 2019)
Four Languages From Forty Years Ago (NewCrafts 2019)Scott Wlaschin
 
Four Languages From Forty Years Ago
Four Languages From Forty Years AgoFour Languages From Forty Years Ago
Four Languages From Forty Years AgoScott Wlaschin
 
The Power of Composition
The Power of CompositionThe Power of Composition
The Power of CompositionScott Wlaschin
 
Designing with capabilities (DDD-EU 2017)
Designing with capabilities (DDD-EU 2017)Designing with capabilities (DDD-EU 2017)
Designing with capabilities (DDD-EU 2017)Scott Wlaschin
 
Designing with Capabilities
Designing with CapabilitiesDesigning with Capabilities
Designing with CapabilitiesScott Wlaschin
 
Dr Frankenfunctor and the Monadster
Dr Frankenfunctor and the MonadsterDr Frankenfunctor and the Monadster
Dr Frankenfunctor and the MonadsterScott Wlaschin
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testingScott Wlaschin
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 

More from Scott Wlaschin (17)

Domain Modeling Made Functional (DevTernity 2022)
Domain Modeling Made Functional (DevTernity 2022)Domain Modeling Made Functional (DevTernity 2022)
Domain Modeling Made Functional (DevTernity 2022)
 
Building confidence in concurrent code with a model checker: TLA+ for program...
Building confidence in concurrent code with a model checker: TLA+ for program...Building confidence in concurrent code with a model checker: TLA+ for program...
Building confidence in concurrent code with a model checker: TLA+ for program...
 
Reinventing the Transaction Script (NDC London 2020)
Reinventing the Transaction Script (NDC London 2020)Reinventing the Transaction Script (NDC London 2020)
Reinventing the Transaction Script (NDC London 2020)
 
The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)
 
Domain Modeling Made Functional (KanDDDinsky 2019)
Domain Modeling Made Functional (KanDDDinsky 2019)Domain Modeling Made Functional (KanDDDinsky 2019)
Domain Modeling Made Functional (KanDDDinsky 2019)
 
Four Languages From Forty Years Ago (NewCrafts 2019)
Four Languages From Forty Years Ago (NewCrafts 2019)Four Languages From Forty Years Ago (NewCrafts 2019)
Four Languages From Forty Years Ago (NewCrafts 2019)
 
Four Languages From Forty Years Ago
Four Languages From Forty Years AgoFour Languages From Forty Years Ago
Four Languages From Forty Years Ago
 
The Power of Composition
The Power of CompositionThe Power of Composition
The Power of Composition
 
F# for C# Programmers
F# for C# ProgrammersF# for C# Programmers
F# for C# Programmers
 
Designing with capabilities (DDD-EU 2017)
Designing with capabilities (DDD-EU 2017)Designing with capabilities (DDD-EU 2017)
Designing with capabilities (DDD-EU 2017)
 
Designing with Capabilities
Designing with CapabilitiesDesigning with Capabilities
Designing with Capabilities
 
Dr Frankenfunctor and the Monadster
Dr Frankenfunctor and the MonadsterDr Frankenfunctor and the Monadster
Dr Frankenfunctor and the Monadster
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testing
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
Swift vs. Language X
Swift vs. Language XSwift vs. Language X
Swift vs. Language X
 
Doge-driven design
Doge-driven designDoge-driven design
Doge-driven design
 
The Theory of Chains
The Theory of ChainsThe Theory of Chains
The Theory of Chains
 

Recently uploaded

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 

Recently uploaded (20)

Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 

Enterprise Tic-Tac-Toe

  • 1. EnterpriseTic-Tac-Toe @ScottWlaschin fsharpforfunandprofit.com In which I ridiculously over-engineer a simple game to create a real-world "enterprise-ready" application. Proper name is "Noughts and Crosses" btw
  • 3. What you need for “Enterprise”? • Siloed organization Specialized teams • ArchitectureTeam • Project ManagementTeam • Front End DevelopmentTeam • Back End DevelopmentTeam • OperationsTeam • SecurityTeam • Compliance and AuditingTeam Can we make them all happy?
  • 4. What you need for “Enterprise”? • Separation of concerns so that specialist teams can work on different parts of the code at the same time. • A documented API so that the different teams can work effectively in parallel. • A security model to prevent unauthorized actions from occurring. • Well-documented design so that the architect can ensure that the implementation matches the UML diagrams. • Auditing and logging to ensure that the system is compliant. • Scalability to ensure that the system is ready for the challenges of rapid customer acquisition.
  • 5. Project Manager: "We need separation of concerns because the front-end team and back- end team hate each other and refuse to work in the same room." Separation of concerns so that specialist teams can work on different parts of the code at the same time.
  • 6. Front-end team: "We need a documented API so that those dummies building the back-end won't keep breaking our code on every commit." A documented API so that the different teams can work effectively in parallel.
  • 7. Back-end team: "We need a security model because those idiots building the front-end will always find a way to do something stupid unless we constrain them." A security model to prevent unauthorized actions from occurring.
  • 8. Maintenance team: "We need well-documented design because we're fed up of having to reverse engineer the hacked-up spaghetti being thrown at us." Well-documented design so that the architect can ensure that the implementation matches the UML diagrams.
  • 9. Testers and Operations: "We need auditing and logging so that we can see what the effing system is doing inside." Auditing and logging to ensure that the system is compliant.
  • 10. Everyone: "We don't really need scalability at all, but the CTO wants to us to be buzzword compliant." Scalability to ensure that the system is ready for the challenges of rapid customer acquisition.
  • 11. I’m gonna use F#, so here’s all the F# you need
  • 12. type Pair = int * int "*" means a pair type Payment = | Cash | Card of CardNumber "|" means a choice typeThing = { name:string } "{" means a record
  • 13. type AFunction = string -> int A Function 42 “Deep Thought”
  • 14. A Function type AFunction = string -> int * bool Input is a string Output is a pair
  • 15. A Function type AFunction = bool * string -> int Input is a pair Output is a int
  • 18. Type driven design • Design with types only – no implementation code. • Every use-case/scenario corresponds to a function type – one input and one output • Work mostly top-down and outside-in – Occasionally bottom up as well. • We ignore the UI for now.
  • 19. Tic-Tac-Toe Scenarios • Initialize a game • A move by Player X • A move by Player O
  • 20. type StartGame = unit -> GameState StartGame Game Statenothing
  • 21. OtherStuff Player X Moves type PlayerXMove = GameState * SomeOtherStuff -> GameState GameState (before) GameState (after) Before After Loop
  • 22. OtherStuff Player O Moves type PlayerOMove = GameState * SomeOtherStuff -> GameState GameState (before) GameState (after)  both functions look exactly the same and could be easily substituted for each other.
  • 23. UserAction Any Kind of Move type UserAction = | MoveLeft | MoveRight | Jump | Fire GameState (before) GameState (after) Generic approach
  • 24. UserAction Any Kind of Move type UserAction = | PlayerXMove of SomeStuff | PlayerOMove of SomeStuff GameState (before) GameState (after) Generic approach applied to this game But we have TWO players so should have two functions....
  • 25. type PlayerXMove = GameState * PlayerX's Stuff -> GameState type PlayerOMove = GameState * PlayerO's Stuff -> GameState Each type is different and the compiler won’t let them be mixed up!
  • 26. What is the other Stuff? For some domains there might be a LOT of stuff... But in Tic-Tac-Toe, it's just the location on the grid where the player makes their mark. type HorizPosition = Left | Middle | Right type VertPosition = Top | Center | Bottom type CellPosition = HorizPosition * VertPosition
  • 27. type PlayerXMove = GameState * CellPosition -> GameState type PlayerOMove = GameState * CellPosition -> GameState Same again 
  • 28. type PlayerXMove = GameState * PlayerXPos -> GameState type PlayerOMove = GameState * PlayerOPos -> GameState type PlayerXPos = PlayerXPos of CellPosition type PlayerOPos = PlayerOPos of CellPosition Different functions Different positions
  • 29. What is the GameState? type GameState = { cells : Cell list } type CellState = | X | O | Empty type Cell = { pos : CellPosition state : CellState }
  • 30. What is the GameState? type GameState = { cells : Cell list } type Player = PlayerX | PlayerO type CellState = | Played of Player | Empty type Cell = { pos : CellPosition state : CellState } Refactor!
  • 31. What is the Output? What does the UI need to know? The UI should not have to "think" -- it should just follow instructions.
  • 32. What is the Output? 1) Pass the entire game state to the UI? But the GameState should be opaque...
  • 33. What is the Output? 1) Pass the entire game state to the UI? 2) Make the UI's life easier by explicitly returning the cells that changed with each move type PlayerXMove = GameState * PlayerXPos -> GameState * ChangedCells Too much trouble in this case
  • 34. What is the Output? 1) Pass the entire game state to the UI? 2) Make the UI's life easier by explicitly returning the cells that changed with each move 3)The UI keeps track itself but can ask the server if it ever gets out of sync type GetCells = GameState -> Cell list
  • 35. Time for a walkthrough... Start game Player X moves Player O moves Player X moves Player O moves Player X moves Player X wins!
  • 36. Time for a walkthrough... Start game Player X moves Player O moves Player X moves Player O moves Player X moves Player X wins! Player O moves Player X moves Player O moves Player X moves Player O moves Player X moves Player O moves Player X moves Did I mention that the UI was stupid?
  • 37. When does the game stop? type GameStatus = | InProcess | Won of Player | Tie type PlayerXMove = GameState * PlayerXPos -> GameState * GameStatus How does the UI know? Returned with the GameState
  • 39. What kind of errors can happen? • Could the UI create an invalid GameState? – No. We’re going to keep the internals of the game state hidden from the UI. • Could the UI pass in an invalid CellPosition? – No. The horizontal/vertical parts of CellPosition are restricted. • Could the UI pass in a valid CellPosition but at the wrong time? – Yes -- that is totally possible. • Could the UI allow player X to play twice in a row? – Again, yes. Nothing in our design prevents this. • What about when the game has ended but the stupid UI forgets to check the GameStatus and doesn't notice. – The game logic needs to not accept moves after the end!     
  • 40. Returning the available moves type ValidMovesForPlayerX = PlayerXPos list type ValidMovesForPlayerO = PlayerOPos list type PlayerXMove = GameState * PlayerXPos -> GameState * GameStatus * ValidMovesForPlayerO type PlayerOMove = GameState * PlayerOPos -> GameState * GameStatus * ValidMovesForPlayerX Now returned after each move
  • 41. What kind of errors can happen? • Could the UI pass in a valid CellPosition but at the wrong time? – No, it is not in the list of allowed moves. • Could the UI allow player X to play twice in a row? – No, the returned list only has moves for Player O • What about when the game has ended but the stupid UI forgets to check the GameStatus and doesn't notice. – The list of moves is empty when the game is over   type PlayerXMove = GameState * PlayerXPos -> GameState * GameStatus * ValidMovesForPlayerO type PlayerOMove = GameState * PlayerOPos -> GameState * GameStatus * ValidMovesForPlayerX 
  • 42. Some refactoring (before) type GameStatus = | InProcess | Won of Player | Tie type PlayerXMove = GameState * PlayerXPos -> GameState * GameStatus * ValidMovesForPlayerO Merge into one type
  • 43. Some refactoring (after) type MoveResult = | PlayerXToMove of GameState * ValidMovesForPlayerX | PlayerOToMove of GameState * ValidMovesForPlayerO | GameWon of GameState * Player | GameTied of GameState type PlayerXMove = GameState * PlayerXPos -> MoveResult type PlayerOMove = GameState * PlayerOPos -> MoveResult
  • 44. Time for a demo!
  • 47. Enforcing encapsulation • Decouple the "interface" from the "implementation". • Shared data structures that are used by both the UI and the game engine. (CellState, MoveResult, PlayerXPos, etc.) • Private data structures that should only be accessed by the game engine (e,g. GameState)
  • 48. Enforcing encapsulation • OO approaches: – Represent GameState with an abstract base class – Represent GameState with an interface – Make constructor private
  • 49. Enforcing encapsulation • FP approach: – Make the UI use a generic GameState – GameState can stay public – All access to GameState internals is via functions • These functions “injected” into the UI With List<T>, you can work with the list in many ways, but you cannot know what the T is, and you can never accidentally write code that assumes that T is an int or a string or a bool. This "hidden-ness" is not changed even when T is a public type.
  • 50. With a generic GameState type PlayerXMove<'GameState> = 'GameState * PlayerXPos -> 'GameState * MoveResult type PlayerOMove<'GameState> = 'GameState * PlayerOPos -> 'GameState * MoveResult The UI is injected with these functions but doesn’t know what the GameState *really* is.
  • 52. move We want to log the input and output. But how? Logging
  • 54. move Logging log Step 2: glue all the functions together using composition log
  • 55. move Logging log Step 2: glue all the functions together using composition log
  • 56. move Logging log Step 3: use the new function in place of old function log There's no need for a "decorator pattern" in FP - it's just regular composition
  • 58. Client-server communication How do you send domain objects on the wire?
  • 59. JSON over HTTP? Enterprise Rating: C-  What communication method should we use?
  • 60. XML & SOAP? Enterprise Rating: A  What communication method should we use?
  • 61. Enterprise Service Bus! Enterprise Rating: A++  What communication method should we use?
  • 62. Sending objects on the wire type MoveResultDTO = { moveResultType : string // e.g. "PlayerXToMove" gameStateToken : string // only applicable in some cases availableMoves : int list } type MoveResult = | PlayerXToMove of GameState * ValidMovesForPlayerX | PlayerOToMove of GameState * ValidMovesForPlayerO | GameWon of GameState * Player | GameTied of GameState Not serialization friendly JSON/XML friendly
  • 64. Stupid people Evil people What’s the difference? 
  • 66. Evolution of a configuration API Say that the UI needs to set a configuration option (e.g. DontShowThisMessageAgain) How can we stop a malicious caller doing bad things?
  • 67. Attempt 1 Give the caller the configuration file name interface IConfiguration { string GetConfigFilename(); } var filename = config.GetConfigFilename(); // open file // write new config // close file API Caller  A malicious caller has the ability to write to any file on the filesystem
  • 68. Attempt 2 Give the caller aTextWriter interface IConfiguration { TextWriter GetConfigWriter(); } var writer = config.GetConfigWriter(); // write new config API Caller  A malicious caller can corrupt the config file
  • 69. Attempt 3 Give the caller a key/value interface interface IConfiguration { void SetConfig(string key, string value); } config.SetConfig( "DontShowThisMessageAgain", "True"); API Caller  A malicious caller can set the value to a non-boolean
  • 70. Attempt 4 Give the caller a domain-centric interface enum MessageFlag { ShowThisMessageAgain, DontShowThisMessageAgain } interface IConfiguration { void SetMessageFlag(MessageFlag value); void SetConnectionString(ConnectionString value); void SetBackgroundColor(Color value); } API  What's to stop a malicious caller changing the connection string when they were only supposed to set the flag?
  • 71. Attempt 5 Give the caller only the interface they need interface IWarningMessageConfiguration { void SetMessageFlag(MessageFlag value); } API  The caller can *only* do the thing we allow them to do.
  • 73. Good security is good design • Filename => limit ourselves to file-based config files. – ATextWriter makes the design is more mockable • TextWriter => exposing a specific storage format – A generic KeyValue store make implementation choices more flexible. • KeyValue store using strings means possible bugs – Need to write validation and tests for that  – Statically typed interface means no corruption checking code.  • An interface with too many methods means no ISP – Reduce the number of available methods to one!
  • 74. Capability based design • In a cap-based design, the caller can only do exactly one thing -- a "capability". • In this example, the caller has a capability to set the message flag, and that's all. Stops malicious AND stupid callers doing bad things!
  • 75. Attempt 5 A one method interface is a function interface IWarningMessageConfiguration { void SetMessageFlag(MessageFlag value); } OO API Action<MessageFlag> messageFlagCapability Functional API
  • 76. Capability Based Security and Tic-Tac-Toe
  • 77. Switching to cap-basedTic-Tac-Toe type MoveResult = | PlayerXToMove of DisplayInfo * NextMoveInfo list | PlayerOToMove of DisplayInfo * NextMoveInfo list | GameWon of DisplayInfo * Player | GameTied of DisplayInfo type NextMoveInfo = { posToPlay : CellPosition capability : MoveCapability } This is a function This is for UI information only. The position is "baked" into the capability
  • 79. HATEOAS Hypermedia As The Engine Of Application State “A REST client needs no prior knowledge about how to interact with any particular application or server beyond a generic understanding of hypermedia.” RESTful done right
  • 80. How NOT to do HATEOAS POST /customers/ GET /customer/42 If you know the API you’re doing it wrong
  • 81. How to do HATEOAS POST /81f2300b618137d21d / GET /da3f93e69b98 You can only know what URIs to use by parsing the page
  • 83. Some Benefits of HATEOAS • The server owns the API model and can change it without breaking any clients – E.g. Change links to point to CDN – E.g. Versioning • Simple client logic • Explorable API
  • 84. Review: How “enterprise” are we? • Separation of concerns • A documented API • Well-documented design type MoveResult = | PlayerXToMove of GameState * ValidMovesForPlayerX | PlayerOToMove of GameState * ValidMovesForPlayerO | GameWon of GameState * Player | GameTied of GameState   
  • 85. Review: How “enterprise” are we? • A security model • Auditing and logging • Scalability You can just waffle here: "immutable" blah blah blah "no side effects" blah blah blah Your CTO will be impressed.   