Sorry this is the last talk of the day so you politte tired I'll try to keep it under now if I can so while everyone's coming in I thought I'd have the slides on the screen and this talk is about the main modeling and how the kind of type system in a function language like f-sharp or Haskell can do a kind of domain modeling that's different and so I thought I'd put up a little quiz at the beginning how many things are wrong With this design so this is how you do it another record type
in F sharp you can see it sort of looks a little bit like Jason and I'm going to ask you how many things along with this and we will through this talk we'll go through and fix them so before we get started on that let's just talk about process so if you think of the software development process like a pipeline if there's an input and do something in this output and we normally focus on the software Development side of things we talk about compilers and tooling and testing and globally value blah because that's what we
care about but just like any kind of process if you have garbage in and get garbage out so no matter how good your your coding is if you have bad requirements or unclear requirements you're going to have a bad product so this talk is really going to focus on the requirements side what does the inputs to our development process The design phase trying to understand the requirements trying to document requirements if we can have good requirements then there's a whole belief that we'll have a decent product so this is the design and that's really the
focus of this talk ok so let's go back to the challenge I gave you before the first thing from this thing is it's not very clear which things are optional in you no strings could be null or something is the first name optional is The middle initial optional is the last name optional some of them are required some of them optional it's not at all clear from this design right so that's a problem in terms of documentation you might have tests in the code you might have a piece of code that says here well this
has to be a non null or non empty before it's loud but that's in the code I'm talking about in the design in this design here that we're looking at so in this case the middle initial is optional And the other fields are required it's not at all clear so that's we're going to try and change our design to fix that what about the constraints can the strings be infinitely long or can they be you know 32 bits long or 64 bits long however long strings you know a couple of gig can they contain non-printable
characters can they attain line feeds you know there's probably some constraints on the string right especially if you have to actually print It out on a mailing label or on a envelope or something or you put it in a database you know for example here we have a constraint that the string can't be more than 50 characters and again you might have some validation rule somewhere but that's not in the design I have to go and try and find out which piece of code has its foundation or than fine fix it what about which feels
a linked so if we have many people using the system and somebody updates the First name when somebody up dates the last name in two different devices is that an error what happens if one person updates the name the other person updates the email at the same time is that an error well in this case the name fields are linked and the email fields are links they have to be updated at the same time atomically but you couldn't if they could be separately bit of one person up it that you mail no there's not being
a name and that's fine and That's not clear from this design either and finding what's the domain logic we have this some flag here is email verified and this is set when you know you put in the email dressing we actually send you back a link and have to click the link to prove that your own that email when is that flag set right under what circumstances is it set it's just a boolean it conveys absolutely things right now you know you have to Read the documentation to find out so that's a really bad design
let's see if we can improve this design as well so in this particular case the logic says if you change the email you have to reset at the false because I need to send you another verification message all right so which value is optional what are the constraints which feels a linked and what's the domain logic f-sharp is great for all this stuff and I think by the end of the talk you'll see what I mean So the main modeling made function lets me get to this talk my name is Claude Russian I have a
web site F sharp on coffee comm so obviously a little bias towards F sharp but these techniques will actually work with any type system like this so a camel or Haskell maybe even Scala so a lot of the ideas in this talk come from the domain driven design book if you haven't read it I highly recommend it but the main point of this book is you focus on the domain Rather than technology okay I don't care about the database I don't care about the web browser I care about what is the business domain what would
people actually care about when they do their jobs that's normally considered sort of a low thing but I like to do it in a functional way so this is a kind of intersection of the functional programming people and the domain modeling people and we're sort of right in the middle here so I'm going to first Of all I'm going to demystify functional programming because a lot of people are scared by functional programming so I always stick this at the bean for my talks I think I won't have to in a few years but for now
I will so if you're not scared affront to the program that's great and then talk about functional programming for real-world applications because a lot of people think it's sort of an academic thing and then I'm going To talk about what is the F sharp type system and why is it different from an object-oriented model of classes and then we'll actually dive into the meat of it and actually design this domain using the types so functional programming sounds very scary because there's always words functor and catabolism and carry ma nodes and the dreaded monad and you
look at all these words and it's like oh my god they're awful you know it's too Way too scary his homer being very scared now I think it's actually not they're scary but it's unfamiliar these are words that you don't know what they mean that doesn't mean you couldn't know what they mean and one of the problems is that the words tend to be kind of mathematical if you rename the words to something like it's a functor as a matter ball so the cat amorphousness a collapsible or something aggregated or attainable these Words would sound
less scary you still wouldn't know they me I mean here's Homer he's still kind of puzzled but it's not it's now just something you just need to learn it's not something so scary that I'm going to give up completely so just be aware that the concepts are actually not that hard it's just the words can be off-putting I tell you what's really scary is on your own you're programming object-oriented program has all these really scary words Like polymorphism and inheritance and interface generics and covariance and solid and solids has five other things inside it and
IO C and di and ABC LM procedure what makes you think that functional programming is bad like object or program is way scarier than front something there's all these things you have to know all these strange terminology you have to understand right this is not scary to you because you probably know other stuff so I guess It's my point is if you know if it seems quite sensible and if you don't know it it seems scary so please don't be put off by the terminology so the thing in this talk is we actually don't need
either stuff in this talk we're not going to be doing any of this stuff no monads in this talk so monad for you talk we're going to be talking about everything else other than blow notes all right so that's my little rant on please don't be scared let's talk about Real-world applications so a lot of people heard that functional programming is good for mathematical stuff and it's good of algorithms and it's good for parallel processing but you need a PhD to understand it right well it's true that it is good for mathematical stuff and it's
good for algorithms and so on but it's not true that you the PhD you can you know like I say it's actually really simple once you get the hang of it so what I think Functional programming is really good for is boring line of business applications okay which I call blubbers so this is what most of us do in our day job probably it's enterprise software it's accountants its inventory management fulfillment ecommerce websites I don't know but it's pretty boring I mean we know mostly it's not exactly the most exciting stuff but if you think
about blob a development there's some things that you really need You need to express requirements clearly because you're trying to communicate with people who are clueless you need a rapid development cycle because you want to get the stuff out there before the first emerge changing their mind you want high quality deliverables because you don't want to have to go back and fix a bug from six months ago when you have swamped with stuff today right so these are very important things and what's interesting is that these are the Same principles of the agile movement has
and they also came from global development they came from a payroll system I think originally so F sharp is really good for this it's very concise it's really easy to do Express requirements clearly and we'll talk about that today it's a rapid development cycle because not only can you do all the unit tests and stuff but you have an interactive environment you can do stuff and it's high-quality to The bubbles and we'll talk about how we can bake quality into the design so we can avoid even writing unit tests and of course the most important
things fund because if you're going to be writing boring business applications and if you have fun doing it okay and it happens a fun is a key word in a shop so there you go all right so here is a cat and a dog and this is like functional programming and beloved elements very happy together all right so domain driven design so for People who don't aren't familiar with domain driven design I'll just quickly go some of the kind of points but the the most important about domain design is about communication is about you have
a model of what you think what you think is happening and the domain experts have a model and often the model of difference and so the point of domains of design is to get your model and the domain expert to share the same model are you basically are working On the same shared mental model because remember it's your model that goes into production right and if your model is wrong the system will not do what it's supposed to do and the domain experts will get angry at you so if you can try and communicate if
you can try and get a shared model going that's great the only way to get a shared model is to have really good communication so let's look at communication so what is this word un IO n is red e okay so some people might Think it's unionize right power to the people and other people especially if you're chemist you might think it's an ionized okay so which one is it which one is it well the answers it's both of course it depends on the context so this is the first point about domain design is there's
a context for everything in business unionized means one thing and in the chemistry context it means an ionized so we have to be very careful about thinking that the Other person understands what we're saying because there might be different words here's another one spam okay in a supermarket spam means canned meat in an email system spamming junk mail right so in the different contexts the same word means something different but okay that's really obvious what about products okay this is where it starts getting painful because in one business the sales team might think of a
product as something you can sell in the Warehouse management team they think of product something that's physically in the warehouse and stuff that you can sell might not be the same things in the warehouse there might be slightly different so there's a potential for confusion here without customer there's another one sometimes you see businesses where they try and create a domain model that stretches over the entire enterprise and everyone is supposed to use the same words that's doomed to Failure because different parts of the business users same words mean different things so in marketing you
know a customer means somebody who can send an email to somebody who can spam in finance world the finance department is somebody who owes you money that's what a customer is so again different definitions other customers and the best way one of them trying to have a generic customer that matches everybody's thing you divide the Business world or the domain into little chunks which is called a context a bounded context and you work inside those chunks now within those chunks the word means the same to everybody but when you cross the boundaries of these chunks
when you get outside your world and then for something else as well it's quite possible the word means something different so another important concept in domain driven design is the concept of a ubiquitous language so ubiquitous Language is the language you use in the shared mental model so a nice a customer and user customer we're talking about the same thing and we have a we need a language to communicate let's all use the same language okay so in chemistry here is the victimís language don't you want to have a polymer now it's very important that
we don't talk techie we don't say a linked list of molecules or something we use the words that the domain experts use which is like a knot In a polymer we don't say a linked list even though we may implement that in our code it's very important that the code uses these terms the same terminology so that when I look at the code I see the domain model and we call this the ubiquitous language and of course every domain has their own ubiquitous language so in sales you might have a product on a customer and
the tracking and again in a different domain same in another side a little bit because Language some of the words are the same but they mean something different because it's a different context so here's some code let's look at actually how you do this can you guess what this code is what kind of domain are we talking about here any ideas well first of all you can see I've got clear there it's a card game now you might think well it's obviously a card game but for example if I didn't say it was a card
game then the word suits could be To do with clothing right and maybe the word hand was something to do with you know medicine doctors as an I don't know but um the fact that there's a card game context then these words make sense within the card game context so that's the bounded context and then this is the ubiquitous language genocide all these are the nouns and the verbs that you use in that context so this is f sharp code let me explain it to you quickly so the vertical bar means a choice so a
suit is A club or a diamond or a spade or heart rank is a two or three or up to an ace the card is a pair so that little thing means a pair and we'll see why we use multiplication giman community R so the card is a pair of a suit and a rank a hand is a list of cards a deck is a list of cards a player is a name plus a hand and a game as a deck that's a list of players the list I just built into a chart is very
nice and here's a verb so when you see this arrow In F sharp that means it's a function so this is a function where the input the thing on the left hand side is a deck and the output the thing on the right hand side is a deck and a card a pair so I can read this and say well the input is a deck the output when ideal is a new deck because the deck is going to be immutable and there's also going to be a card on the table so that's what the output
is and when I pick up a card from the table the input is my hand and the Card on the table that's the input the pair and the output is my new hand and the card on tables disappeared so this is a documentation of that the nouns involved and the verbs involved so here's a question do you think this is a reasonable amount of code to write to document this domain basically a page code I would say yeah not bad I've got like you know nine different things on on one slide pretty good do you
think a non programmer could understand this if I if I was showing it something I say you know I'm not sure you know is there is a diamond one of the suits or something they could correct me and say yes it is I know it isn't whatever you know if I've missed something they could probably check it one of the things about this model is it's what we call persistence persistence ignorant there's nothing about databases there's nothing about foreign keys There's nothing about primary keys there's nothing about tables there's nothing about classes there's nothing about
inheritance there's nothing about interfaces there's nothing except the domain this is purely all about the domain this is why it's called the main driven design is not called object-oriented design it's not called database driven design domain dove in design the whole point is to focus on what's important in the Domain and everything else is irrelevant right now so what's interesting is the design this is the design and it's also compatible code one of the goals of agile development you know is to make the code be the design because if you have the design and the
separate UML diagram or a separate document it's always going to get out of sync so you can keep the design and code in sync that's fantastic and the best way to keep the design and the code in sync is To be its have the design in the code so I think this is a great example of how you can do this so this is not pseudocode this is executable code you could stick this is like the first file in your f sharp project and it kind of defined the domain for the rest of the project
so we don't need any stinking UML diagrams in our F sharp driven design here all right so that's the basics of domain driven design I kind of like the key Ideas so let's look at the F sharp type system and C wise I think it's really good for doing this the exit up type system is what they call an algebraic type system algebra just like X's and Y's and adding and multiplying things we'll see it's a kind of mathematical word so I actually prefer composable so composable means you can glue things together like Lego and
you can build bigger things from smaller things so there you go this and Lego right so in The F sharp license well first of all F sharp types are not they're just data structures so they don't have any behavior which means it's really easy to glue them together because you don't have to worry about what is the behavior of them when they're going to get that as a different problem so to create a new type you can just glue them together in two different ways you can multiply them together and you can add them together
okay now that Sounds a bit weird but how can you not apply a type how can you add a type what does it mean so let's look at what this means okay so here's a function and we're going to use the classic thing as a functions with a box and there's an input and as an output so for example the add one function the input is a list of numbers so the input is one of the integers from the list of integers and the output is another one of the integers from the disturbances okay and
In F sharp we write this as an int arrow int meaning enters the input and enters the output with the error telling you there's a function so that's how you you know there's a set of integers which could be the possible inputs what happens if the input is a pair let's say we want to add a pair of numbers together and and you know the output we can say well that's an integer but what is the input how can we define what the input type is when in object-oriented Would would define a pair class we're
not going to do that we're going to build a class we're going to build a type by composing listing types right so let's have a look at this if you think about it the pair means you have a pile you take one from the first pile and one from the second pile right so if there are four things in the first pile and there are four things in the second pile how many possible pairs are there altogether 16 yes four times four There's 16 possible combinations all right so this is this is where the multiplication
comes in okay what about if you have a pair of boolean's okay so there's two possible billions in the first pile to possible Williams in the second pile how many possible pairs are there there's four possible pairs it's two times two so we call this a we call them like multiplying the types so a pair of intz is written is in two times int and a Pair of billions is written as all times ball okay so that's why we use the multiplication and we call these kinds of things product types prototypes so here's an example
use okay works very theoretical let's look at a real example let's say we want to model people's birthdays okay so what is a birthday well a birthday is a person and a date I mean get a pick a person a typical date that makes somebody's birthday so we're going to say well there's all the Possible people and all possible dates and the combination you multiply them together gives you all the possible birthdays all right so we're just going to say a birthday is a person times a date so that's our type we've created a new
type that we can actually use in our code the representatives all right so that's the multiplication and I also said you can add types together what does that mean so let's say we have a function that tells you whether you have A fever or not so we're going to pass in your temperature and it's going to return a boolean true or false but the problem is is the temperature in Fahrenheit or is it in Celsius well we want to design our function so that works with both of them so the input is a Fahrenheit or
Celsius how can we model them well let's say that there are four possible Fahrenheit temperatures obviously they're more than that and let's say there are four possible Celsius temperatures how many possible inputs are there eight thank you there's eight there's four possible from this but it's 4 from this part or 4 from this part so that's eight possible combinations and that's why we call it an addition right because it's this pile plus this part now in this case they might both be integers or something so we need to distinguish between the Fahrenheit cases and the
Celsius cases so when we write our code we're going to Have to tag saying well this is the found high case this is the Celsius case and we write you like this we say the temperature type is a choice between an F where there's an insulated with it or a sea where there's a float associated with it so that's how rude right a choice type or some type okay it's a choice between these two things and this is the kind of type that you don't have in c-sharp this is very unique to sort Of functional
programming so choice types are really really useful for domain modeling I mean here is a payment method and it says okay this is a cash there's a choice there's three choices you can take cash you can take a check or you can take a credit card if you take cash there's no other information associated with it if you take a check there's a check number if you take a credit card there's a pair and the pair is a card type and a card number so in This one type we've actually got quite a lot of
domain knowledge very compactly written make sense so there we go check number and so what's nice is each choice can have its own set of data associated with it now once we've got one of these choice types how do we actually work with it and this is where the concept called pattern matching comes in so let's say we have a payment methods if we want to print it the way it works is we Basically deconstruct it in the same way that it was constructed so we have to have a case there's three possible cases in
the data type so we have to have three possible choices when we analyze it so we do this match it's like we're going to do a pattern match and there are three possible cases the first cases is cash the second case is a check and the third case is as a card and what's interesting is when it does the deconstruction it also extracts the Associated data so you don't have to like find out like you know deficit is it this kind of class and then if it's this kind of class cast it to a class
and then the extracting it does it all in one step very nice so if you think about the object-oriented version of this so I wanted to implement this kind of payment method in our what I'd pull in to do is create you know a base class or interface or something and then I have to create three separate sub Classes that implement that payment method that's fine but it's kind of annoying because this interface there's nothing in there there's no common behavior it's just data so this would be a like a method list interface or marker
interface which is always kind of a bit of an anti-pattern and and the other problem is the you doing c-sharp you probably have a different file for each of these things so your code is sort of scattered all around and your your data Modeling code is going to mixed in with your implementation code which is kind of annoying if you wanted to find out all the methods you'd have to look at all the different files and most importantly I think is that this is it with inheritance it's an open set of choices write anything that
implements I penguin ethic is valid so for example if I create a thing called evil and it implements our payment method that will be fine now sometimes that is useful to Be able to extend the thing but often in business modeling you actually want a restricted set of cases it's like I only accept these three payment methods just add another paint method without like changing quite a lot of stuff in the business it's not just as simple as inheriting from something and implementing you know this has to be more complicated than that so if you
go to the F sharp model what's nice is that all the choices in one Place and it's a closed set of options it's like you know exactly it's only these three choices and the extra data that put these choices right there in your face you don't have to like search or management class it's right by pair so from a modeling point of view this kind of approach is very very nice so if you think about types in most programming languages we think of types is sort of a an annotation that helps you type check you
know you make sure This is integer it's not a string it's not a boolean so we think of it's just something that helps the compiler you know stay accurate but what we're doing here is we're doing using types as a terrain modeling tool so when we say that we're dealing is a deck and you know the inputs and the outputs and stuff this is not about type checking this is about modeling your domain so we're using types for two things and what's cool is that in a language like F Sharp you can get both at
once you get the type checking and you also get the domain modeling which means that the type checker the compiler can check your domain logic for you okay so if you have a good static type system it's almost like having compile time unit tests you literally will not be able to write code that doesn't match the domain model you don't have to write a a unit test to test something because it literally won't compile it is wrong and we'll see An example of that shortly so type all the things it's all very good all right
so there's the type system now let's take it out for spin let's see what can we do with it so the first thing is we talked about we want to have some sort of optional values right we want to say something's optional we don't want it to be you know we want to make it very clear there's optional so how can we do that so here's our is our personal name and that will The middle one is optional so how do we represent optional values well let's kind of go back the beginning let's say that
we have a length function that takes a string as input and spits out an int as output right so the input is a list of possible Springs now one of the problems in most type systems is that null is a valid string okay null is in the list of things that you can pass into this function and that's a problem because know is not a string you can't Set phasers to no it just doesn't make any sense you know so this null is really bad having null as a valid value for a string is really
bad because it's not really a string it's pretending to be a string but when you actually use it it will blow up in your face the compiler work captured the compiler says yeah sure null so string no problem and then when you try and access the length of the string of in a crash so I like to say that null is sort Of the cerumen of static typing he's going to pretend to be your friend is going to stab you in the back when you're not looking so so okay so nulls are really bad so
in functional languages nulls are not allowed to be part of the bad set of values okay so we can't model an optional thing by saying yeah we just use null to me that's missing what we really want to do is model it using what we described you want to say well it's either you know a Valid string or it's missing okay how can we model that in our type system well I think we've seen this it's either one of these things or it's one of these other things so we model it as a choice it's
either a string or it's a nothing all right so it's a it's a plus source of some type so we're going to tag the top one with some string and we're going to tag the bottom one with nothing and then we can define a type like this is optional string it's either something And there's a string associated with it or it's nothing all right so this is how we would model an optional string using our very cool type system alright this is awesome and we get very excited by this and say yeah optional strings fantastic
and then actually we also need an optional integer oh yeah we need an optional boolean and I think you can see there's something wrong with this because there's quite a lot of duplicate code so This is where we say okay let's not rewrite this over and over every possible type let's make it generic version okay and here's the generic version it's called option it's a built-in type in a sharp you don't have to define it and that little tick T is f sharp spy of saying it's a generic so in c-sharp it doesn't have a
ticket and intercept it does have a tick so that's a generic type and then we can say okay so the Middle initial is not just a string it's an option of a string and one of the nice things in F sharp is you can actually put it backwards you can see as a string option so this looks very nice I think if I say first one's a string second one's an optional string and the third one's a string that's a nice design and it's captured the intent of which ones are required and in F sharp
if it's if it's not optional it's required that's basically a rule of Thumb all right another kind of thing we can do is what I call single choice types so a single choice type is one of these choice types except there's only one choice right so hopefully here's an email and there's only one choice of email here's another one customer ID and there's only one choice customer ID why would you do something as silly as only having one choice all right well if you think about It an email address isn't a string it's a wrapper
for a string right it may be represented as a stream kind scene but that email address is not a string because there's constraints around it it has to have an out sign and it has to be less than hundred characters and you know and so on so it's not just a normal string a custom ID is not an integer it might be represented by an integer in your database but it's not that industry you can't add five to a customer ID you Can't you know take the square root of a custom idea just just making
sense so these things are not you have to make a distinction between what it is whether the main point of view and what it is from the representation point of view and what we want to do is represent there's a thing called an email address in the domain there's a thing called accustom ID and they are distinct the fact that there's a representation behind the scenes is Not relevant to the domain model so what we do something like this an email address is an email address it wraps a string but it's not a string a
phone number wraps a string but it's not a string and as soon as we do this we now have distinct types so an email address and a phone number and now different types and it cannot be mixed up you can't accidentally pass a phone number to the email address okay even even though the strings behind the scenes They're now completely different types and of course you can do this in object you could create a special object that contains a value it's different and for example custom ID and an order ID there are different types right
you shouldn't mix up an order ID in a custom ID that could be really bad so doing these single choice types allow us to do that so let's create the email address so we pass in a string and we have some horrible regex that checks whether it's Got an out sign in it or whatever so if it does match the regex we're going to wrap that string in the email address and return it and if it doesn't match the regex what are we going to do we're going to throw an exception we're going to return
null oh you can't do that what we need to do is say ok you gave me a string that I can't handle I have to give you nothing back so what we have to do is make a distinction between something and Nothing so rather than just giving you the emails respec I'm going to give you some email address back and if it doesn't work I'm going to give you nothing back so if you look at the type signature the original one said you give me a string and I'll give you back an email address and
it's like no you give me a string and I might give you back an emitters I'll optionally give you back images if you give me a good string and if you Don't give me a good string I'll give you nothing back so now what we've done is it's now in the dock that the code is being document is documenting the fact that it might not always work I think so well than just throwing exception I don't have to read the documentation I can just look at this and says yeah you know you might not work
there's some validation going on another very useful type is a constrain string right we have you know a string that has to be 50 Characters or less and we do the same things like if the length is 50 is good and if the length is not 50 it is longer than 50 or something that's bad so again if we look at the signature you give me a string and I might give you back a string 50 or I might not so you have to handle that but in F sharp these things are immutable so once
you have got a string 50 or once you've got an email address you never have to check it ever again nobody can change it after it's Been created so you never have to do any kind of defensive programming the initial thing of like when you've loaded from the database so you've parsing the JSON for whatever's you have to do this checking but after that you never have to check whether it's null you know how to check whether it's valid you never have to check it is it going to fit in the database because the strings
too long so the defensive programming sort of goes away once you've done the Initial has been a foundation of the edges of your app there's a lot less code you have to write inside the app here's another good one this is a website they need and you can order nine hundred nine nine thousand nine or nine nine things that's a problem that's probably a bug why is it bug because the person writing website probably isn't int as their quantity right so that's not that's not right how can we stop people using an int well we
say okay We're not going to use me we're going to use a special type called an order line quantity it's different from in it it's the main specific type it's just for this particular domain an order line as a special thing it's not a normal in again you can't multiply it by five and stuff so we're creating a new type just to represent one thing in the domain okay and how many people ever do this how often do you write a new class just to represent a little thing like an Integer a lot of times
we can't be bothered because it's too much work and then one of these days we have a bug because we have a negative number in our order qty or something this one you can never have a bug because let's say we we can do the validation when we plate it and if it is valid it's a new one and if it's not valid it's a bad one so again once we've got this or line quantity it's immutable it can never change and it can never be bad we never have to Check it ever again all
right so let's revisit the challenge we had our original contacts so the first thing we did is we recreated the way of making optional stuff really visible it was this different type the second thing is we now have special types for each of these wheels to make it very clear it's not just a normal string it's a 50 character string it's not just a string is an email address okay by creating special types this is Now more self documenting and it's also more self validation - the other thing is we talked about is keeping them
separate well of course it's really easy we just create two separate types each one is an atomic thing and then we create a new contacts which has the name and the email content info so we've now made it very clear that these are separate on of things and we can now pass this in when we persist these things we can say well I want to save The person lame I want to save the email contact info those will be separate transactions and the daily basis of a we don't have to worry about them climbing all
right there's one thing we forgot about which is this email verified flag so let's have a look at that in more detail there's some rules around this okay if the email has changed we have to reset it to false okay and we should have a rule that we can only set the verified flag by special verification Service because when we verify you know you click the link in the some kind of hash code you check the hash code matches the email and if that's all good we've got a very email we want to make sure
that rule is followed we don't want anyone just verifying it because that could open us up it could be a security issue if I could if I could hack into the system and change the email verify flag then I could send myself a password reset message you know to the wrong Email address and so on so it's really bad we really want these rules to be followed as it stands now the design does not communicate these rules so can we embed these rules in the design okay not in some documentation not in some piece of
code that checks validation something literally in the design so that's the next challenge all right so right now anyone who set this true there's nothing it's just asking for trouble All right so what we're going to do is create a new type and one of the rules in domain modeling in a sharp is there's no problem that can't be solved by wrapping it in another type okay so we have our email address type and we're going to wrap it in another type called a verified email all right we're going to take and get another type
and now we're going to have our verification service and the verification service for its input it takes a normal email Address and it takes some sort of hash and it spits out a verified email or maybe not it's maybe the verification verification has doesn't match so it's very clear that this is returning you know you give me email address I might give you back a verified email so it's now very clear you can tell straight away from this didn't mind our work you don't have to look and see does it throw an exception or something
and then what we also do is make this verify the email Type a private constructor so that the only person who created is the verification service so that's just like any any kind of thing you can just make it a private sort of type and then now we do now we go back now we've got this thing we go back to our original thing and we say rather than saying there's a flag we say it's a choice so it's either an unverified email address or it's a verified verified email address okay so there's a choice
of two things and What's cool is that in order to use the unverified choice all we need is a regular email address and I can create an email that's that's fine but to create the verified choice I'm going to need a verified email where can I get a verified email form well I can't create it myself because it's private the only way I can get a verified email is from the verification service because it's the only one has permission to write it so by doing this I have actually Embedded those business rules right in the
design okay I've guaranteed I don't have to write a unit test for this anymore because the code is the design could capsulate those rules and not only does that it also you know looks nice okay we'll see in a minute so here's our self completed challenge email address we've got all these new types before we had one type and now we've got email address you've got a verified email as I Male contact okay we've got a personal name we've got a contact we've got spring 50 in Ozone so let's go back and visit the challenge
which manager optional what the constraints which feels linked and what's the domain logic so we can clearly see which values are optional because they've got an option next to it okay that's right in in my face I don't have to go and read the documentation what the constraints will is really obvious this is a 50 character String this is a 1 character string and so on again I don't have to read the documentation I don't have to dive into the code looking the validation rules or anything which feels a links we've now broken the original
thing into two these pieces I can show you haven't got every detail in here but you could also show that they get updated separately and it's the domain logic clear yes so before we had a boolean flag and now we Have a choice and what's interesting is that the bigoted language the set of words that we use to talk about the domain has evolved as we've done this process because originally we just had you know a contact and everything was a string and a boolean and now we have things like we have a concept called
an email address and we have a concept called a verified email address and we have a concept called a personal name and a concept called an email contact And so on this is these are the words that business reduce I mean we've actually discovered something not only have we got a better design we've also got a design actually reflects the terminology that the business would use when they're talking about this thing so this is good so we've actually killed two birds with one stone better design and a more accurate characterization of the model from a
business point of view and of course This is all compatible code this is not a Word document and this is not a UML diagram all right let's do one more thing making illegal states unrepresentable so sometime later we decide to add an address so well as having an email a contact could have an address and a postal address as well okay fair enough now the business says you know we need a business rule a contact must have an email address or postal address Sounds sensible all right so let's look at this design does this design
meet the requirements right it's like we've got these two fields email and address right no it doesn't because remember what I said everything is required unless you say it's optional is required so this design says that the email and the address are both required fields that's not what I said I said I could be one or the other right all right let's make them both optional well that doesn't Work either because they could both be missing and that doesn't meet the rule either we said we need to have one or the other right but they
can't both be missing so how can we model this okay there's a great phrase make illegal states unrepresentable so rather than saying okay well they can't both be missing but we'll put a unit test in we'll put some validation in we'll try and make sure that never happens it's like no don't do that try and make sure The design captures the business rule so you literally can't happen you literally cannot light codes that doesn't meet the business rule okay how can we do that well if you think about it a contact must have an email
or post address what does that mean well it means that you either have an email us or they have a personal address or they have both okay that's three possibilities those are the three possibilities and then missing other than missing there's not a Possibility so there's three choices how do we model something with three choices well we've seen how to do this right we say well it's an email only or lesson dress only or it's both so now we have a type the represents of three choices and what's great about this is like the choice
where they're both missing is not an available choice it literally cannot happen there's not the top fold will not compile it's just not there not only that it also documents it communicates If I come across this code and I say well you know what are the business rules around these things it's like well yeah you can either have one or even how the other wouldn't have both so it's a self-documenting code which is very nice and then we take this choice and we stick it in our context so the requirements are now included in the
type system we don't have to write unit tests that's great the code is also self documenting which is great All right so we can build this thing up now we've got yet another type okay we start off with one type now we have like twenty types so the types really not apply luckily they're all really short and they all fit in one page so that's good so before they were separate and after afterwards we've merged them into one time all right this is awesome so static types for domain modeling they're almost as awesome as a
cat on a unicorn not maybe not as quite as awesome but I Think they're pretty awesome let's do one mother one more little tweak chances are the business doesn't really want that rule that's what they said they wanted as always what they say the one is maybe not what they really want and now go back to them and say is that what you really want so actually now all we want is we have to have at least one way of being contacted okay I don't care first of all incentives kind of looks kind of ugly
so we just say you have to Have at least one way up in contact it's fine how do we model that well we say here's all different ways you can be contacted you can be contacted by email who can be contacted by postal address we could add you know Twitter or Skype or something those are different ways have been contacted and then when we have a contact we have two fields one is the primary contact info and the second second one is the secondary contact enter and it's very clear from this Design that the primary
one is a required fields and the second one is optional so you have to have at least one way of being contacted and you might have a second way of being contacted as well it's not quite the same because you could have two email addresses this officer it's not exactly the same logic as the previous one so let's look at what we've covered I talked about this challenge right could we make that original design better I talked about Your victus language I talked about self-documenting designs I talked about algebraic types and products and sums and
using choices to model things rather than inheritance this would kind of key takeaway and then we talked about designing with types and using options instead of null using these single case unions to wrap types and making illegal states representable kind of trying to capture the domain rule in the pipe system directly so that's a Good time to stop there I think there's a lot of things I can't cover right now I could talk about states state machines that's a really interesting one how does services work and love of law there's lots of stuff to talk
about but I'm not going to talk about them thank you for just the end of the day so okay the slides and the video for this talk will be on my website if shop for fun and profit coms slash DVD and in fact they're already there because I've Done this talk before so if you want to see this talk again or you want to look at the slides that's all there if you want consulting business F sharp works if you want to know more about F sharp if you think their shop is just awesome go
to F sharp that all you can download it it's a cross-platform language it works on a Mac it works on Linux it works in Visual Studio but it also works in vs codes you don't need to have a whole video studio thing if you don't Want to and you can also join their shop foundation for free and then participate in the slack channel and finally I have a book coming out soon called domain modeling main functional what a coincidence the same title as let's talk so it's just the it's in the early access it's in
the beta right now it's not finished you can buy it now if you like if you want if you're desperate to read it or you can wait a couple of months and you can get it when it's Finally ready but I hope you will like it it's basically the store extended into a book and I think that is it so thanks very much and of course feel free to grab me ask questions whatever and there's a by the way if you're interested in a shop there's a functional lab every day at 1:40 it's in room
10 you have to go out the towards its front and then go up the stairs so if you if you want to see some demos of this I can demo this stuff to You directly if you're interested so definitely check out the functional lab Cheers