Latest / CyberSecurity Summary / Functional Programming in C#: How to write better C# code
Transcript
- 0:00Speaker 1: Imagine you're curled up in your favorite chair right deeply
- 0:04Speaker 1: engrossed in this fantastic mystery novel.
- 0:06Speaker 2: Oh it sounds like a great afternoon.
- 0:08Speaker 1: Yeah, exactly. You're following the plot, picturing the characters. But
- 0:11Speaker 1: there's just one massive problem.
- 0:15Speaker 2: Okay, what is it?
- 0:16Speaker 1: Someone else is standing right next to you frantically flipping
- 0:18Speaker 1: the pages of your book back and forth while you're
- 0:21Speaker 1: trying to read it.
- 0:22Speaker 2: Oh wow, that sounds incredibly frustrating.
- 0:24Speaker 1: Right, I mean, one second you're on chapter three and
- 0:26Speaker 1: then boom, you're staring at the epilogue.
- 0:28Speaker 2: Yeah, that would drive me crazy, exactly.
- 0:31Speaker 1: And that chaotic, unpredictable, pull your hair out mess that
- 0:36Speaker 1: is exactly what happens inside your software when concurrent programs
- 0:41Speaker 1: share mutable state.
- 0:42Speaker 2: It really is the ultimate concurrency nightmare. You know, you
- 0:46Speaker 2: have one thread trying to read a sequence of data,
- 0:49Speaker 2: and then another thread is mutating or like physically changing
- 0:53Speaker 2: that exact same data right out from under you. Yeah,
- 0:56Speaker 2: and it's the root cause of so many unpredictable bugs.
- 1:00Speaker 1: Today's deep dive is all about stopping that page flipping.
- 1:03Speaker 1: We're exploring the surprisingly practical world of functional programming, but
- 1:08Speaker 1: we're doing it inside language. Most people associate strictly with
- 1:12Speaker 1: object oriented programming, which is C shark, right, and we're
- 1:16Speaker 1: pulling our insights from Enrico Banana's book Functional Programming in
- 1:19Speaker 1: C Sharp. The mission here is to basically act as
- 1:23Speaker 1: a shortcut for you, because you absolutely do not need
- 1:26Speaker 1: a PhD in mathematics to use these concepts.
- 1:29Speaker 2: No, you really don't.
- 1:30Speaker 1: We're going to look at how functional techniques can you know,
- 1:32Speaker 1: drastically reduce bugs, handle concurrency almost effortlessly, and just make
- 1:37Speaker 1: your code based so much more readable.
- 1:39Speaker 2: Yeah, and I think that's important because functional programming often
- 1:41Speaker 2: gets this unfair reputation for being overly academic.
- 1:46Speaker 1: Yeah, totally, like it's just Ivory Tower stuff exactly.
- 1:49Speaker 2: But when you actually apply it to real world line
- 1:52Speaker 2: of business applications in C sharp, it becomes this highly
- 1:55Speaker 2: pragmatic tool set. It really boils down to changing two
- 1:59Speaker 2: ingrained like how we treat our data and how we
- 2:02Speaker 2: treat our behavior.
- 2:03Speaker 1: Well, let's start with behavior then, because that ties right
- 2:05Speaker 1: into how we manage the flow of an application.
- 2:08Speaker 3: In c sharp.
- 2:09Speaker 1: Functions aren't just invisible blocks of code anymore. They are
- 2:14Speaker 1: what we call first class values, which means you can
- 2:17Speaker 1: take a function, assign it to a variable, or pass
- 2:20Speaker 1: it as an argument into another function, just like you
- 2:23Speaker 1: would with a regular string or an integer.
- 2:26Speaker 2: Yeah, and we use delegates and lambed expressions to do this,
- 2:29Speaker 2: and treating functions as data. It unlocks one of the
- 2:32Speaker 2: most foundational tools in functional.
- 2:33Speaker 1: Programming, a higher order function.
- 2:35Speaker 2: Exactly the higher order function people usually just shorten it
- 2:38Speaker 2: to HOF. HOF is simply any function that either takes
- 2:42Speaker 2: another function as an input parameter or returns a function
- 2:46Speaker 2: as its output.
- 2:47Speaker 1: Right, And thinking about this in real world terms, using
- 2:50Speaker 1: a HOF feels a lot like hiring a subcontractor oh
- 2:54Speaker 1: I like that? How so Well, take the lanq wear method,
- 2:58Speaker 1: which we use to filter lists all the time in
- 2:59Speaker 1: C sharp. In this scenario, where's the manager. It handles
- 3:02Speaker 1: all the tedious border plate stuff, setting up a loop,
- 3:05Speaker 1: managing the index. You know, all the mechanical parts.
- 3:08Speaker 2: Right, the stuff you don't want to write over and
- 3:10Speaker 2: over exactly.
- 3:11Speaker 1: Yeah, But the manager doesn't actually know what you're looking for,
- 3:13Speaker 1: so it subcontracts the decision making logic asking like should
- 3:18Speaker 1: I keep this specific item? It delegates that to the
- 3:21Speaker 1: function that you pass into it.
- 3:23Speaker 2: That is a perfect analogy. The division of labor is
- 3:25Speaker 2: so clear. The hof handles the mechanics and you supply
- 3:29Speaker 2: the unique business logic.
- 3:31Speaker 1: Yeah.
- 3:31Speaker 2: Another incredibly practical application for this is encapsulating set up
- 3:36Speaker 2: and tear down logic. Think about how often you interact
- 3:41Speaker 2: with the database. Oh, all the time, right, and you
- 3:44Speaker 2: always have to do the same dance. You acquire a connection,
- 3:47Speaker 2: open it, do your work, close it, and then dispose
- 3:50Speaker 2: of the resource.
- 3:50Speaker 1: Oh man, the endless using blocks You end up copying
- 3:54Speaker 1: and pasting those same five lines of code across like
- 3:56Speaker 1: fifty different repositors.
- 3:58Speaker 2: So repetitive. But with a higher order function, you can
- 4:00Speaker 2: just write a custom using function one single time. Oh right.
- 4:04Speaker 2: That one function handles opening the connection and disposing of
- 4:08Speaker 2: it in a finally block, and you just pass it
- 4:10Speaker 2: a function that represents the specific query you want to
- 4:13Speaker 2: run in the middle.
- 4:14Speaker 1: That's brilliant. It completely eliminates all that boilerplate duplication exactly.
- 4:18Speaker 1: So Okay, the manager handles the subcontractors, the code gets cleaner.
- 4:22Speaker 1: But even the best manager can't fix a job site
- 4:26Speaker 1: if the blueprints keep magically changing while the crew is
- 4:29Speaker 1: reading them.
- 4:30Speaker 2: Right back to the page flipping problem.
- 4:32Speaker 1: Exactly which brings us to this second habit.
- 4:34Speaker 3: We have to change.
- 4:35Speaker 1: We have to avoid state mutation, right.
- 4:38Speaker 2: And mutating state simply means changing and existing value in
- 4:42Speaker 2: place and memory. For instance, if you have a list
- 4:45Speaker 2: of numbers in C sharp and you call list sort,
- 4:49Speaker 2: the framework physically rearranges those items in your computer's memory.
- 4:53Speaker 1: Right, it's a destructive update. The original order is just
- 4:55Speaker 1: gone forever.
- 4:56Speaker 2: But if you use LA and Q's order by method,
- 4:59Speaker 2: it behaves complete lely differently. It doesn't touch your original list.
- 5:02Speaker 2: It reads it and then creates a brand new list,
- 5:04Speaker 2: a new view of the data that happens to be sorted.
- 5:07Speaker 1: Leaving the original completely intact.
- 5:09Speaker 2: Exactly, And that distinction might seem minor, but it is
- 5:13Speaker 2: exactly what saves you from the concurrency disaster. Buanano's book
- 5:17Speaker 2: has this terrifying example of this.
- 5:19Speaker 1: Oh yeah, the math there one, right.
- 5:21Speaker 2: Imagine a background task Task one. It's trying to calculate
- 5:25Speaker 2: the sum of a massive list of numbers running from
- 5:28Speaker 2: positive ten thousand all the way down to negative ten thousand.
- 5:31Speaker 1: Okay, so logically, if you add all those up, the
- 5:33Speaker 1: sum should perfectly balance out to zero.
- 5:35Speaker 2: It should, But imagine that at the exact same millisecond.
- 5:39Speaker 2: Task two is concurrently running on a different thread, and
- 5:42Speaker 2: it calls list sort on that exact same list.
- 5:45Speaker 1: Oh no, because list sort mutates the list in place.
- 5:49Speaker 1: Task one is trying to do math, while task two
- 5:52Speaker 1: is aggressively moving the numbers around exactly.
- 5:54Speaker 2: Task one might read the number five thousand, and then
- 5:57Speaker 2: task two moves that five thousand further down the.
- 5:59Speaker 1: List, and this one just reads it a second time.
- 6:01Speaker 2: Right, so the result isn't zero, the book points out,
- 6:04Speaker 2: You get these bizarre, totally unpredictable results, like returning a
- 6:08Speaker 2: sum of nine, three hundred thirty nine and seventy.
- 6:11Speaker 3: That is wild.
- 6:12Speaker 2: And this is why concurrency and traditional imperative programming is
- 6:15Speaker 2: so notoriously difficult. You have to introduce complex locks, You
- 6:18Speaker 2: have to freeze the entire list just to read it,
- 6:20Speaker 2: which just destroys your performance.
- 6:22Speaker 1: But if you embrace immutable data, where sorting creates a
- 6:26Speaker 1: new list instead of destroying the old one, concurrent reads
- 6:31Speaker 1: don't cause any inconsistencies whatsoever.
- 6:33Speaker 2: Right, you get parallelization essentially for free, because nobody is
- 6:37Speaker 2: flipping the pages of the book you are trying to read.
- 6:39Speaker 1: I mean, if you've ever stared at a massive, tangled
- 6:42Speaker 1: legacy code base and felt sheer panic at the thought
- 6:46Speaker 1: of making it thread safe. Realizing that avoiding mutation gives
- 6:49Speaker 1: you a free pass to parallel execution is just a
- 6:53Speaker 1: massive light bulb moment.
- 6:54Speaker 2: It really is.
- 6:55Speaker 1: And taking this idea of avoiding mutation to its logical
- 6:59Speaker 1: extreme brings us to the concept of the pure function.
- 7:03Speaker 2: Yes, the pursuit of purity is central here. A pure
- 7:06Speaker 2: function closely resembles a mathematical equation. It operates under two
- 7:10Speaker 2: very strict rules. First, its output depends entirely and exclusively
- 7:14Speaker 2: on its input arguments okay, And second, it causes absolutely
- 7:18Speaker 2: no side effects.
- 7:19Speaker 1: Now, side effects is a really broad category, right, We
- 7:21Speaker 1: aren't just talking about mutating global variables. In functional programming,
- 7:25Speaker 1: throwing an exception is considered a side effect. Yes, it
- 7:27Speaker 1: is performing any kind of IO like printing to the console,
- 7:31Speaker 1: querying a database, or even just checking the system clock.
- 7:34Speaker 3: Those are all side effects.
- 7:36Speaker 2: Right, And people always ask why is checking the clock
- 7:38Speaker 2: a side effect? It's because anytime you rely on the
- 7:41Speaker 2: external physical world, your function loses its determinism. Oh, if
- 7:46Speaker 2: a function asks the system for the current time to
- 7:49Speaker 2: validate a token, it will return a different result tomorrow
- 7:52Speaker 2: than it did today, even if you pass in the
- 7:55Speaker 2: exact same token.
- 7:56Speaker 1: Right, whereas a truly pure function guarantees the exact same
- 7:59Speaker 1: output every single time until the end of the universe exactly.
- 8:03Speaker 2: The book contrasts two string manipulation functions to show why
- 8:07Speaker 2: this matters for scaling up. One is a pure function
- 8:10Speaker 2: called toe sentence case. It just takes a string and
- 8:12Speaker 2: formats the capitalization super simple. The other is an impure
- 8:15Speaker 2: function called pre pend counter. It takes a string, but
- 8:19Speaker 2: it also reaches outside itself to use the plus plus
- 8:21Speaker 2: operator to increment a shared global counter variable, so it
- 8:25Speaker 2: can number the strings.
- 8:26Speaker 1: And if you try to run that impure pre pen
- 8:29Speaker 1: counter in parallel across a million strings, it falls apart
- 8:34Speaker 1: because at the CPU level, plus is actually multiple steps
- 8:37Speaker 1: read the value, add one, write it back.
- 8:40Speaker 2: It's not atomic, right, Multiple threads read the shared counter
- 8:43Speaker 2: at the exact same millisecond, they all add one to
- 8:46Speaker 2: the same base number and write it back. They trample each.
- 8:48Speaker 1: Other, so you lose thousands of updates.
- 8:50Speaker 2: Yeah, your final count will be completely wrong. But the
- 8:53Speaker 2: pure to sentence case function, you can spread that across
- 8:56Speaker 2: one hundred different CPU cores instantly.
- 8:58Speaker 1: Because it doesn't rely on anything else side itself, it
- 9:01Speaker 1: is completely isolated, which means it's thread safe by default exactly.
- 9:06Speaker 2: And that complete isolation is why pure functions are an
- 9:09Speaker 2: absolute dream to unit test. You don't need to configure
- 9:12Speaker 2: dependency injection or complex mock objects. You just feed it
- 9:16Speaker 2: an input and assert the output.
- 9:18Speaker 1: Whereas testing in pure io is usually a nightmare. To
- 9:21Speaker 1: test a service that happens to check the time, developers
- 9:23Speaker 1: usually resort to creating these totally hollow header interfaces. You
- 9:28Speaker 1: end up creating an I date time service and wiring
- 9:30Speaker 1: it up everywhere solely so you can inject a fake
- 9:34Speaker 1: frozen clock into your unit test to mock DateTime dot
- 9:37Speaker 1: ut as nail.
- 9:39Speaker 2: It hadds so many layers of boilerplate just to test
- 9:42Speaker 2: a simple date validation. The functional approach solves this by
- 9:46Speaker 2: pushing the pure boundary outwards.
- 9:48Speaker 3: What do you mean by outwards?
- 9:49Speaker 2: Instead of injecting a massive mocked interface that goes out
- 9:52Speaker 2: and gets the date, just inject a hard coded daytime
- 9:55Speaker 2: value directly into your validator as an argument.
- 9:58Speaker 1: Oh, so the val itself stays.
- 10:01Speaker 2: Pure exactly, Or if you need to validate against a
- 10:04Speaker 2: list of valid bank routing numbers from a database. Don't
- 10:07Speaker 2: inject an entire I repository interface. Just in ject a
- 10:10Speaker 2: simple function like a delegate returning a list of strings
- 10:13Speaker 2: that the validator can invoke.
- 10:14Speaker 1: Okay, wait, I'm trying to picture an application built entirely
- 10:17Speaker 1: like this, a program with absolutely no IO.
- 10:19Speaker 3: It's basically just a space heater.
- 10:21Speaker 1: A space heater, yeah, I mean it consumes electricity, gets
- 10:24Speaker 1: a CPU hot, and does absolutely nothing useful. We have
- 10:27Speaker 1: to have side effects, right, we have to save to
- 10:28Speaker 1: databases and display things on screens.
- 10:30Speaker 2: That is a very valid reality check, and functional programming
- 10:34Speaker 2: absolutely acknowledges that the goal was never to eliminate IO entirely.
- 10:39Speaker 2: It is to isolate it.
- 10:40Speaker 3: Okay.
- 10:41Speaker 2: The book uses a document converter application called pandock to
- 10:45Speaker 2: illustrate this architecture. You isolate the pure computational core, the
- 10:49Speaker 2: complex logic of parsing, markup, translating, syntax, formatting, the layout
- 10:54Speaker 2: that is all pure, and then you wrap that core
- 10:57Speaker 2: in an impure IO shell. The shell handle reading the
- 11:00Speaker 2: original file from the hard drive and writing the final
- 11:03Speaker 2: PDF back to the disc.
- 11:04Speaker 1: Oh I see, so you actively push the MESSI impurity
- 11:07Speaker 1: to the very edges of your application exactly.
- 11:10Speaker 2: You keep the messy real world on the outside and
- 11:12Speaker 2: your core business logic pure on the inside.
- 11:15Speaker 1: But that raises a major question about error handling. If
- 11:18Speaker 1: our pure functions aren't allowed to throw exceptions, how do
- 11:21Speaker 1: we handle bad data?
- 11:23Speaker 2: Right?
- 11:23Speaker 1: Like, if someone passes my pure function and negative age
- 11:26Speaker 1: and I can't throw an argument exception, what are we
- 11:28Speaker 1: supposed to do?
- 11:29Speaker 2: This brings us to the concept of making our function
- 11:31Speaker 2: signatures honest. A signature, its name, inputs, and return type
- 11:35Speaker 2: is essentially a contract, right.
- 11:38Speaker 1: It tells the caller what inputs it requires and what
- 11:40Speaker 1: output it guarantees.
- 11:42Speaker 2: Exactly, and the book highlights how easily we lie in
- 11:45Speaker 2: these contracts. There's an example of a dishonest signature, a
- 11:48Speaker 2: function named calculator risk profile that takes the standard integer
- 11:52Speaker 2: for the age parameter.
- 11:53Speaker 3: Okay.
- 11:54Speaker 2: The signature promises that if you give it any integer,
- 11:57Speaker 2: even negative one thousand, it will successfully return a risk profile.
- 12:01Speaker 2: But inside the body it checks if the age is negative.
- 12:04Speaker 2: If it is, it throws an argument exception and halts
- 12:06Speaker 2: the program.
- 12:07Speaker 1: It's a completely dishonest contract. The caller reads the signature
- 12:11Speaker 1: assumes they're safe providing any integer, and then at runtime
- 12:14Speaker 1: the app violently crashes.
- 12:16Speaker 2: Exactly functional programming actively avoids hidden traps like this.
- 12:20Speaker 1: So how do we fix a dishonest signature without throwing
- 12:23Speaker 1: an exception? We use a pattern called a smart constructor.
- 12:26Speaker 1: Instead of accepting a raw integer for age, we define
- 12:30Speaker 1: a custom immutable age type and we write a smart
- 12:33Speaker 1: constructor method like age two seat. This runs the validation
- 12:37Speaker 1: logic before the age object is ever allowed to be created.
- 12:41Speaker 2: By enforcing that validation upfront, you make invalid states unrepresentable
- 12:46Speaker 2: in your system. Once your code holds an instantiated age object,
- 12:50Speaker 2: you know for a fact it contains a valid positive age.
- 12:54Speaker 1: So your calculat risk profile function changes its signature to
- 12:58Speaker 1: require an age type instead of integer.
- 13:00Speaker 2: Yep, the signature becomes completely honest and the function never
- 13:04Speaker 2: has to worry about throwing an exception for negative numbers. Ever.
- 13:07Speaker 1: Again, that makes perfect sense for a validation. But what
- 13:10Speaker 1: about retrieving missing data? Because the standard dot net collections
- 13:14Speaker 1: drive me a little crazy with their inconsistency here how so, Well,
- 13:18Speaker 1: if I use a name value collection and ask for
- 13:20Speaker 1: a dictionary key that doesn't exist like green, it quietly returns.
- 13:24Speaker 3: A null value.
- 13:25Speaker 1: But if I use a standard dictionary and ask for blue,
- 13:27Speaker 1: it throws a keynot found exception.
- 13:29Speaker 2: Oh yeah. Under the functional paradigm, both those outcomes, returning
- 13:33Speaker 2: a silent null or throwing a loud exception are considered dishonest.
- 13:37Speaker 2: If a function goes looking for a value and might
- 13:39Speaker 2: not find it, its signature needs to explicitly declare that
- 13:43Speaker 2: failure is a distinct possibility. This is where we introduce
- 13:46Speaker 2: the option type.
- 13:47Speaker 1: The option type you might hear it called maybe in
- 13:50Speaker 1: other languages. It essentially models data that might be absent yes.
- 13:55Speaker 2: It has two possible states, some and none.
- 13:59Speaker 1: I like to vision the option type as a cardboard
- 14:02Speaker 1: shipping box. You order a new gadget online. When the
- 14:06Speaker 1: delivery arrives, the box either contains the gadget you wanted.
- 14:09Speaker 1: That's the sum state, or there was a warehouse mix
- 14:12Speaker 1: up and the box is empty, which represents the nun state.
- 14:16Speaker 1: That's a great visualization, but crucially, either way, the delivery
- 14:19Speaker 1: driver still handed you a physical box. You can safely
- 14:23Speaker 1: hold it, pass it to another department, and write code
- 14:25Speaker 1: to handle the box without your program crashing.
- 14:27Speaker 2: Exactly, instead of returning null, which is just a ticking
- 14:31Speaker 2: time bomb that causes a null reference exception. The second
- 14:34Speaker 2: you try to access it you return an option. It
- 14:36Speaker 2: explicitly communicates to the developer the statu might be absent.
- 14:39Speaker 2: You are forced to handle the empty box scenario.
- 14:42Speaker 3: Hang on, though.
- 14:43Speaker 1: Let's say a business requirement changes marketing decides that the
- 14:47Speaker 1: first name field on a massive newsletter sign up form
- 14:50Speaker 1: should now be optional. If I go into my C
- 14:53Speaker 1: sharp domain model and change the first name property from
- 14:56Speaker 1: a regular string to an option string, every single piece
- 14:59Speaker 1: of code in my application that touch's first name is.
- 15:02Speaker 3: Going to break immediately. It won't even compile.
- 15:05Speaker 1: How is breaking the bild a good thing?
- 15:08Speaker 2: It is actually a fantastic thing, because you're trading silent,
- 15:12Speaker 2: unpredictable run time crashes for loud immediate compile time errors.
- 15:17Speaker 2: Think about the alternative. If you just allowed that string
- 15:20Speaker 2: to be null, your code would compile perfectly fine, but
- 15:23Speaker 2: it would crash in production a week later the very
- 15:25Speaker 2: first time user didn't enter their name and a downstream
- 15:28Speaker 2: system tried to call to Hupper on it ah right.
- 15:31Speaker 2: By changing the signature to an option, the compiler becomes
- 15:33Speaker 2: your personal assistant. It flags every single place in your
- 15:36Speaker 2: massive codebase that needs to be updated to acknowledge this
- 15:39Speaker 2: new optional reality.
- 15:41Speaker 1: Okay, I see the safety in that. Yeah, but it
- 15:43Speaker 1: brings up a huge logistical headache.
- 15:45Speaker 2: What's that?
- 15:46Speaker 3: If we safely pack our.
- 15:47Speaker 1: Missing data into these option shipping boxes, how do we
- 15:51Speaker 1: actually do any work on the data inside the box.
- 15:54Speaker 1: Like if I have a pure function that expects a
- 15:57Speaker 1: regular string, but my database returned in an option string,
- 16:01Speaker 1: I can't just pass the box to the function. Do
- 16:03Speaker 1: I have to write an if statement every single time
- 16:06Speaker 1: to check if the box is empty, unpack it, run
- 16:09Speaker 1: the function, and repack it. That sounds exhausting it.
- 16:12Speaker 2: Would be, but you don't have to do that manually.
- 16:15Speaker 2: That is exactly where we introduce the core functional design
- 16:18Speaker 2: patterns functors and monads, which are operated by the map
- 16:22Speaker 2: and bind functions.
- 16:23Speaker 1: I know, the terms functors and monads sound incredibly intimidating.
- 16:27Speaker 1: They sound like advanced category theory.
- 16:29Speaker 2: They do carry a lot of academic baggage, but stripped
- 16:32Speaker 2: down to their basics, they are just patterns for structures
- 16:34Speaker 2: you already use every day. An option or an I
- 16:37Speaker 2: innumerable list. Those are containers. They represent values existing at
- 16:41Speaker 2: an elevated level of abstraction.
- 16:43Speaker 1: So let's demystify the functor first, which relies on a
- 16:46Speaker 1: function called map. The map function reaches into your container,
- 16:50Speaker 1: takes the inner value out, applies your regular business logic
- 16:53Speaker 1: function to it, and then reboxes the new result back
- 16:56Speaker 1: into a new container, and you never have to write
- 16:59Speaker 1: an if statement to check if the value is actually there.
- 17:03Speaker 2: If the option box happens to be in the nun state.
- 17:05Speaker 2: If it's empty, Map is smart enough to just bypass
- 17:08Speaker 2: your function entirely and return a new none. If it
- 17:11Speaker 2: is in the sum state, it applies the function and
- 17:14Speaker 2: wraps the result in a new sum. It completely abstracts
- 17:18Speaker 2: away the boilerplate of checking for the absence of data.
- 17:21Speaker 1: The book has an amazing analogy to explain map. Think
- 17:24Speaker 1: of your aunt who absolutely loves baking apple pies.
- 17:28Speaker 2: Okay, I love this one.
- 17:29Speaker 3: You leave a.
- 17:30Speaker 1: Basket of apples on her front porch. The basket itself
- 17:33Speaker 1: is the option container. The apples are the concrete value
- 17:36Speaker 1: inside her baking skills represent your business logic function. You
- 17:41Speaker 1: leave the basket, She takes the apples out, bakes a pie,
- 17:45Speaker 1: and puts the pie back into the basket. What started
- 17:48Speaker 1: as an option of apples is now an option of pie.
- 17:50Speaker 2: And how does she handle an empty basket?
- 17:52Speaker 1: That's the brilliance of map. If you leave an empty
- 17:54Speaker 1: basket of bandit yeah, yeah, none, she doesn't freak out,
- 17:58Speaker 1: She doesn't throw a null reference exception or call you
- 18:00Speaker 1: in a panic. She just smiles and leaves the empty
- 18:03Speaker 1: basket right there on the board exactly. You don't have
- 18:04Speaker 1: to explain to her what to do with empty space.
- 18:07Speaker 1: The map process handles the empty state automatically.
- 18:10Speaker 2: That analogy perfectly captures how a functor works, but we
- 18:14Speaker 2: inevitably run into a more complex scenario. What happens if
- 18:18Speaker 2: the function you are applying also returns an option container?
- 18:22Speaker 3: Oh? I see?
- 18:23Speaker 1: Like if I have an option of a strength from
- 18:25Speaker 1: a database and I pass it to a parsing function
- 18:27Speaker 1: that tries to turn it into an integer, that parsing
- 18:30Speaker 1: function might fail, so it returns an option of an integer, right,
- 18:34Speaker 1: and then I pass that integer to our smart constructor
- 18:36Speaker 1: for age, which also returns an option of age.
- 18:38Speaker 2: Precisely, if you use the standard map function to string
- 18:42Speaker 2: those operations together, you have a structural problem.
- 18:44Speaker 1: Let me think about how the generic types would stack up.
- 18:48Speaker 1: Map always puts the result in a new box. So
- 18:51Speaker 1: if my function returns an option age and Map puts
- 18:53Speaker 1: that result in a box, I end up with an
- 18:55Speaker 1: option containing option containing an age. Yeah, it's like Russian
- 18:59Speaker 1: nesting dolls of day option age. That sounds impossible to
- 19:03Speaker 1: work with.
- 19:03Speaker 2: It is very clunky, and that exact problem nested containers
- 19:07Speaker 2: is where monads and the bind function come to the rescue.
- 19:10Speaker 3: Okay, so what does bind do.
- 19:12Speaker 2: Bind does the exact same conditional execution as MAP, but
- 19:16Speaker 2: it has a special power. It flattens the result. Instead
- 19:20Speaker 2: of handing you nested boxes, Bind unwraps the inner box
- 19:23Speaker 2: and hands you a single flat optionage.
- 19:26Speaker 3: Oh wow.
- 19:27Speaker 1: To adapt the ant analogy, it's like if the ant
- 19:29Speaker 1: bakes the pie, but you put the pie into her
- 19:31Speaker 1: own special pie basket. If you used map, you'd come
- 19:35Speaker 1: back to find your porch basket containing her pie basket
- 19:37Speaker 1: containing the.
- 19:38Speaker 2: Pie, right, which is just silly.
- 19:40Speaker 1: But Bind is the process where she realizes that's ridiculous,
- 19:43Speaker 1: takes the pie out of her basket and just puts
- 19:46Speaker 1: it directly into yours.
- 19:47Speaker 3: You get one flat basket.
- 19:48Speaker 2: That is a brilliant way to conceptualize flattening. So map
- 19:51Speaker 2: is for applying regular functions and bind is for applying
- 19:54Speaker 2: functions that themselves return Containerska.
- 19:57Speaker 3: It makes sense.
- 19:57Speaker 2: And finally there's four each which we use right at
- 19:59Speaker 2: the very end of the pipeline. We use map and
- 20:02Speaker 2: bind to run all our pure logics safely inside the containers,
- 20:05Speaker 2: and then we use four each to safely execute our
- 20:08Speaker 2: impure side effects like physically writing to a database.
- 20:11Speaker 1: But it only executes if the data actually made it
- 20:14Speaker 1: through the entire pipeline without turning into a nun exactly.
- 20:17Speaker 1: So we have all the building blocks on the table.
- 20:19Speaker 1: Now we have pure functions, honest signatures via smart constructors,
- 20:23Speaker 1: option types to handle missing data, and map and bind
- 20:27Speaker 1: to process logic without if statements. You do, how do
- 20:31Speaker 1: we actually string all of this together to build a
- 20:33Speaker 1: real end to end architecture.
- 20:36Speaker 2: Well, we build functional workflows using function composition and method chaining.
- 20:40Speaker 2: We're used to this in object oriented code, where you
- 20:42Speaker 2: chain methods together with dot notation. The data flows linearly
- 20:46Speaker 2: reading from left to right.
- 20:48Speaker 1: Li inq is probably the best example of this workflow
- 20:50Speaker 1: mindset that see sharp developers already use. Definitely, if you
- 20:53Speaker 1: want to find the average earnings of the richest core
- 20:55Speaker 1: tile of a population. You don't write nested for loops
- 20:58Speaker 1: and temporary variables. You write a declarative chain you call
- 21:02Speaker 1: order by descending then dot, take dot, select dot average.
- 21:05Speaker 1: It's flat readable and defines the pipeline perfectly.
- 21:09Speaker 2: Now, let's elevate that LA and Q mindset and apply
- 21:12Speaker 2: it to a real server side scenario from the book.
- 21:15Speaker 2: Dealing with the fictional bank of code Land.
- 21:17Speaker 3: Okay, Bank of code Land.
- 21:19Speaker 2: We receive a web request to process a make transfer
- 21:22Speaker 2: command between two bank accounts.
- 21:24Speaker 1: Right, and in a traditional imperiadive web controller, that code
- 21:28Speaker 1: gets messy fast. You have an if statement to check
- 21:31Speaker 1: if the request is null, then a trycatch block around
- 21:34Speaker 1: the database lookup inside that. Another is statement checking if
- 21:38Speaker 1: the account balance is high enough.
- 21:39Speaker 2: Yeah. It creates this deeply nested arrow code that is
- 21:42Speaker 2: really hard to scan.
- 21:44Speaker 1: But by utilizing our functional building blocks, the entire web
- 21:47Speaker 1: controller can be rewritten to read like a single flat sentence.
- 21:51Speaker 2: It really is striking to look at.
- 21:53Speaker 1: Translating the code into plain English. The pipeline flows exactly
- 21:56Speaker 1: like this. You lift the raw transfer request into an
- 21:59Speaker 1: option box. You map it through a function that normalizes
- 22:01Speaker 1: the text, you filter it through a wear clause that
- 22:04Speaker 1: validates the accounts, and if and only if it survives
- 22:08Speaker 1: all those steps without turning into a hote none, you
- 22:11Speaker 1: call for each to execute the side effect that physically
- 22:14Speaker 1: books the transfer.
- 22:15Speaker 3: In the ledger.
- 22:16Speaker 2: Every step is isolated. You never have to manually check
- 22:19Speaker 2: for nulls, and you never have to catch a validation
- 22:22Speaker 2: exception because the option context handles the flow control for you.
- 22:25Speaker 1: It is incredibly elegant. But when we look at the
- 22:29Speaker 1: domain model for actually booking that transfer, things get a
- 22:33Speaker 1: big controversial.
- 22:34Speaker 2: Out the OP versus FP modeling.
- 22:36Speaker 3: Yeah.
- 22:37Speaker 1: In the book's comparison, the traditional object oriented account object
- 22:41Speaker 1: has a debit method. You pass it an amount, it
- 22:45Speaker 1: checks its own balance, it mutates its internal state to
- 22:48Speaker 1: lower the balance, and it throws an exception if you
- 22:50Speaker 1: don't have enough money.
- 22:52Speaker 2: Which, as we've established, breaks all our rules. It relies
- 22:55Speaker 2: on hidden state mutation and throwing an exception makes it
- 22:58Speaker 2: an impure, dishonest signature.
- 23:01Speaker 3: Right.
- 23:01Speaker 1: But the functional replacement they propose strips the behavior completely
- 23:05Speaker 1: out of the object. We get an account state object
- 23:07Speaker 1: that is essentially just dumb immutable data with public properties. Yes,
- 23:12Speaker 1: and the actual debit logic is moved to a pure
- 23:15Speaker 1: static function that takes the old state as an argument
- 23:18Speaker 1: and returns an option account state containing the new balance.
- 23:21Speaker 1: I have to say I struggle with this. For decades
- 23:24Speaker 1: we've been taught that OP is fundamentally about encapsulating data
- 23:27Speaker 1: and behavior together inside objects. Splitting the account state.
- 23:32Speaker 3: Data away from the debit logic feels like we are.
- 23:34Speaker 1: Abandoning OOP and going backward to procedural programming from the
- 23:37Speaker 1: nineteen seventies. Why is tearing encapsulation apart considered better?
- 23:42Speaker 2: It is a very common reaction to feel like separating
- 23:45Speaker 2: data and behavior is a regression, but in this context
- 23:48Speaker 2: it's actually an elevation of your architecture. How So, in OOP,
- 23:52Speaker 2: tightly binding data and behavior inside a single object often
- 23:55Speaker 2: leads to hidden side effects and unpredictable state mutation over time,
- 24:00Speaker 2: and as we saw with the sorting concurrency disaster, mutable
- 24:02Speaker 2: state causes massive bugs when systems scale. By separating them,
- 24:06Speaker 2: account state becomes a pristine, thread safe snapshot in time.
- 24:10Speaker 2: It can never be corrupted by a background threat.
- 24:12Speaker 3: Oh, I see, And the.
- 24:13Speaker 2: Pure static debit function doesn't need tate anything. It simply
- 24:17Speaker 2: evaluates the pristine snapshot runs the math and securely calculates
- 24:21Speaker 2: the next step in the pipeline. It makes your workflows
- 24:23Speaker 2: highly composable.
- 24:25Speaker 1: Because you can pipe the output of debit directly into
- 24:27Speaker 1: the next function without ever worrying that some internal property
- 24:31Speaker 1: was secretly altered or that a hidden exception is about
- 24:35Speaker 1: to blow up your call stack.
- 24:36Speaker 2: Exactly so, it's not about regressing to procedural spaghetti code.
- 24:40Speaker 2: It's about making the business logic mathematically predictable and completely
- 24:45Speaker 2: testable in isolation.
- 24:47Speaker 1: That makes a lot of sense. Functional programming in C
- 24:50Speaker 1: Sharp isn't about throwing away the language features. It's about
- 24:53Speaker 1: using them to build a highly pragmatic, incredibly resilient tool set.
- 24:58Speaker 2: That's the perfect way to summarize it.
- 25:00Speaker 1: Let's quickly recap the mission we set out on today.
- 25:03Speaker 1: By treating our functions as data that can be passed around,
- 25:06Speaker 1: by rigorously avoiding state mutation, and by utilizing honest structures
- 25:10Speaker 1: like the option type, paired with map and bind, you
- 25:12Speaker 1: can make your c shark code incredibly concise. Absolutely, you
- 25:16Speaker 1: can almost entirely eliminate null reference exceptions because the compiler
- 25:19Speaker 1: forces you to acknowledge missing data and most importantly, you
- 25:23Speaker 1: make concurrency a breeze because immutable data simply does not
- 25:26Speaker 1: suffer from raise conditions.
- 25:28Speaker 2: It definitely requires a paradigm shift in how you view
- 25:31Speaker 2: dataflow and state mutation, but the payoff in reliability and
- 25:35Speaker 2: reduce debugging time is immense.
- 25:37Speaker 1: To wrap up, I want to leave you with a
- 25:39Speaker 1: provocative thought to molover. If we can elegantly represent the
- 25:44Speaker 1: total absence of data using just the option type Wait,
- 25:48Speaker 1: I mean think about that. And if we can completely
- 25:51Speaker 1: remove nested if statements from our web controllers using map
- 25:54Speaker 1: and wear pipelines, what other traditional imperative control structures could
- 25:59Speaker 1: we entirely replace?
- 26:00Speaker 2: That's a great question.
- 26:01Speaker 1: Could functional wrappers entirely eliminate the need for trycatch blocks
- 26:04Speaker 1: in your application? Could they replace traditional wile loops? How
- 26:08Speaker 1: much shorter and how much more bulletproof could your legacy
- 26:10Speaker 1: codebase become? If you started thinking impure functions today, maybe
- 26:14Speaker 1: it is finally time to stop the frantic page slipping
- 26:16Speaker 1: in your software and just enjoy the book.