Union Types Broke My Build (And That's the Point)
Read full transcript 12 segments
-
Hey, my name is Milan and in this video I want to take a deeper look at what we can do using union types in C 15. In fact, we can leverage union types and the C compiler to help us enforce our code into a good structure. Let me show you what I mean. I'll use the result pattern as the basis for my discussion. And previously without union types, the entire result pattern could grow to dozens or even hundreds of lines of code depending on how many helper methods you want to define. With union types, I purposefully turned it into just one line of code where we wrap either a specific type representing our success value or an error representing our failure case. And this is definitely useful in defining some pretty expressive code that can have a finite set of cases. So it can either succeed where we return our happy path in this case just the identifier of a new booking that we create inside of our reserve booking handler or one of a couple of possible failure cases represented with an error value. Now how do we consume this? Well, we consume union types using a switch expression.
-
And in the program CS, I'm just setting up a couple of helper instances, mainly a handler along with its validation decorator. The validator is just an inline function that checks that the start and end date are valid. I've got a couple of commands that I execute in a loop and then I print out the result of the command. Now, this is the important part how we consume a union. We do a switch expression and then we match based on the types inside of our union because this is a result containing a good as a value. We can match on this path representing our success case and we return a mocked 2011 created response. In all the other cases we return an error. And here in lies the problem with our result monad defined by a single line union. We lack some capabilities that allow us to leverage the C# compiler. Take a look at this pattern match here where we are matching based on our error path. But we don't have a nice way to match to a specific error other than doing a pattern match on the code property. And this is all nice and fine, but it becomes a problem when we introduce a new business rule.
-
For example, we now also check inside of our handler that each apartment must have some sort of minimum stay. So we calculate the start and end day of our reserve booking request. And if that number is less than the minimum nights for that apartment, we return a new stay to short error. And why this is problematic is because now our code still compiles, but someone and that someone is the developer or more realistically an AI agent now has to know that they also need to add check here for this new business rule. If I open up a terminal and I run net build, you're going to see that the build still passes because nothing is enforced by the compiler. And if I do a net run, you're going to see that we're going to get the respective response for each of our command instances. And the last one, which triggers the minimum stay rule on purpose, defaults to a 500 internal server error. And this really isn't something that you want. You typically want to map this to a 400 bad request response. Now the solution would be to add another case here where we would match on the stay too short error. But I want to show you a better way how we can instantly use the C# compiler to let us know that we now have a missing case so we can never forget to add it. So let me show you how we can achieve this using a slightly different monad from our initial result union. So what I'm going to do is create a new type here. I'll
-
call it reserve booking outcomes. Let's place it in the same name space as everything else. And then what I want to do is make all of our possible cases including the happy path and the failure cases into concrete types. And I think you're going to quickly see where this is going. So I'll create a booking reserve type. And this is going to contain the booking ID. And then I want to map my possible error cases, the ones we have here, into concrete types. So I'm going to drop them in. And these are just going to be records that represent an apartment not found failure, an overlap failure, or a state to short failure. The advantage is we can now also include the concrete values as properties and then process them in some way that we find suitable. And finally, what this allows us to do is to define a union type representing a reserve booking error. And as you might have guessed, this is going to contain the types that we just defined here. So these are going to be apartment null found, overlap or stay to short, which we defined above. So now we've got a failure case that represents one or more failure rules and a happy path encapsulating the identifier of a newly created booking. And now we just need some sort of monad that's going to allow us to wrap this structure. A result monad isn't quite suitable because it only wraps a type and a predefined error. So I'm going to create a new one and I'll call this an outcome. You're
-
going to see it with similar names out there. Often also called an either monad, but I'm going to call it outcome and it's going to be a union again. So let's call it the outcome union. And I still want it to be generic. Now the generic parameters are going to be a T and a T error. And this allows me to define the type that represents my happy path or success case. I can also have a generic type for the error case. And it's also not a bad thing to have some sort of fallback for things that we don't want to include inside of our T error parameter. So I'll create a record called validation failed. We're just going to have a message property there. So, slightly different structure than the result monad, but it's still a monomad. And if you're wondering what a monad is, it's just a wrapper around the type that allows us to get the value, which we can do by accessing the value property or in a cleaner way using the switch expression. And it allows us to map it to a different monad. And then another thing we need is a method that allows us to chain a call that also returns another wrapped value or another monad. Now, this is a bit complex, so I'm going to leave it for the end of the video, but you'll see that it's conceptually just a couple of methods that we're going to add to the outcome union. They don't functionally affect what I want to show you in this video, but they do help to produce a more cleaner syntax. Okay, we've got our outcome or e monad. How do we use it?
-
Well, we can go to the reserve booking handler, and we're going to update our I handler here to change what we return. So instead of a result containing a good we're going to return an outcome and this outcome can be either a booking reserved or it can be a reserve booking error. I will have to update my return type here in the handle method to accommodate for this and then the rest of the things we have to do are just going to be some boring refactoring steps. Nonetheless, let's just do them. So instead of returning an error that could previously easily map to a result union, we have to return a reserve booking error here. However, what we defined is an apartment not found instance that contains the apartment ID. Now, we can't automatically convert this into our new union type. And this is because there's no implicit conversion from apartment not found into an outcome union. However, we can cast this to a reserve booking error and this can implicitly convert to our new union type. Now, there is a way to go around this which I honestly wouldn't recommend as it would involve typing a bunch of code and in this case it's going to be a public static implicit operator. If you've done C for years, you probably know about this, but essentially this allows us to define an implicit conversion operator. And what we want to
-
do is convert to an outcome that returns a booking reserved instance or a reserve booking error. And then the arguments are going to be this same instance. So apartment not found. And if I go back to our handler, you'll see that now this isn't required because it's redundant. And we can just return the new error type. But having to do this for all my failure cases is a bit annoying, at least to me. So I'm going to leave it in the code so you can check it out, but I'm going to comment it out and go back to a cast here. Now let's do the other errors. So we've got stay too short and what we do is define a new stay to short instance, pass it the minimum number of nights and we cast this to a reserve booking error. The same goes here. We cast it to a reserve booking error and we return a new overlap error which is part of our union. So I'm going to map from the command my start and end dates and I've handled my failure cases. Now what about the success case? Previously we were returning a booking ID but now we have to return a booking reserved instance and luckily this just maps to the outcome without any issues. So that's it for the refactorings inside of our reserve booking handler. So our validation decorator was previously using the result monad and I'm going to drop in a new one that uses the outcome monet. So a couple of notable changes is
-
obviously we now return an outcome and our validation function returns a validation failed instance instead of an error. And this is only done so that we can return the failure here and have it map to the outcome union because it's part of the union type definition. We also have to update the handler instance here. And again, I'm going to comment out the previous one and drop in the new one so that we can see them side by side. But it's still pretty boring refactoring, just converting the result to an outcome and adding a couple of different types. And also making our validation function return a validation failed instance. We just have to do a couple other things. First, make the handler return an outcome. Then we're going to pass this outcome to the respond method. And I will update the respond method to process an outcome using the switch expression. So let me move this into a new line. And this is where we have to make our final adjustments. So now we are processing the possible branches of our outcome union. And these are going to be a booking reserved instance. So that's our first case. And we map this to a 2011 created by passing in the booking ID to the message that we return from this method. So we've got our happy path, we've got our error path, and in this case, because the outcome has three types, we also have the validation failed path. And this is essentially our fallback. So in this case, we're going to process validation failed as one of the possible union types. And I'm going
-
to make this just return a 400 bad request. Now, for the error path, we'll be able to get rid of all of this because we're going to match on the reserve booking error. Now this is also a union. So what we do is chain another switch expression and this is the actual payoff. So now because we have a union type defining our error cases, we have to exhaustively process every possible branch. So let's comment out what we had previously and let's say we process one of the possible failure cases which is apartment not found and we're going to map this to some sort of 404 not found response. We also have, for example, an overlap that we can map to a 409 conflict response. And I'm going to stop here and I want to point you to this squiggly line under the switch keyword. It says that the switch expression does not handle all possible values of its input type. It is not exhausted. For example, the pattern bookings stay too short is not covered. With the previous implementation, when we add a new error code, our code still compiles fine and we don't get any warnings. In this case, we at least get a compiler warning. So, if I do net build, we'll get a warning in the output letting us know, hey, there's potentially something wrong with your code. Now, how can we leverage this? We can open our project file and turn on warnings as errors for this specific error code. Although I would recommend turning warnings as errors on
-
for all possible errors and just getting rid of them from your code. It's a pretty satisfying way to develop C# applications. So now this turns into a compile error and in turn I can no longer do a net build as my build is going to fail. So now I'm forced to add the missing statement and this is just adding a case here saying stay too short. Let's call this too short. And we map this to a 400 bad request. And after we've done this, we have covered all the possible cases. We can go ahead and build a solution. The build is going to pass and we can do net run and it's going to run our code through all of the available commands. And you'll see that each one gets mapped to the proper response. Now, another thing I want to point you to here is that I'm passing along the entire record to our interpolated string. And you can see in the response in prints out the record type name and its property values. So if you want a different error response, you would just have to process this separately. And we've managed to improve our code into a state where there are no exceptions. Our code can either succeed or fail defined by our outcome monad or union type which makes the reserve booking handler deterministic easier to test, easier to extend, and easier to understand for you as well as your agent. And I think it's going to become very important in the future that we can produce code that can be more correct to put it like that. With exceptions, you never really know what you get. But with
-
functional paradigms like using monads in this example, your code is a lot more deterministic. And I have a hunch, although it's not really tested in practice, that this is going to let agents produce better code and code with fewer bugs, which is something I think all of us want. One more thing I want to show you for the end is that you can also add methods to your union types. So this is just like any other type inside of C. So it can hold methods and a couple of those that you would typically find on a monad are going to be a map method that allows you to map the value that you are wrapping from one type into another. You can also do a bind which is basically a function that can potentially fail. So the return type of this function is an outcome. Whereas with a mapping, it's just a different type and mapping cannot fail. And then we've got another helper method called match that just allows you to match on the possible types inside of the monad. And I think my solution is a bit too practical with three types in the union, but it allows me some flexibility, which is why I use it in this example. So we just define a function for our success path for the error and for the validation fail as a default case. Now in this case we also need to handle the null branch. And this is because the compiler cannot determine that the object instance that's wrapped by the strct that the union is converted to would potentially be null at runtime. So it forces us to also handle the null
-
case in the switch expression to make it exhaustive. But we don't really expect this to ever be null. So we can just throw an invalid operation exception as this is actually an exceptional case in our codebase. And then finally, let me show you how we would use this helper method. I'll define a helper called summarize that takes in an outcome, maps it to a different type. Now notice that this takes in a booking reserve and maps it to its raw value, the good. Then it does a match on the outcome. And it has a different function for the success, the failure path for the validation failure. And we could call this inside of our loop right below the respond call. And if I go and do a net run here, you're going to see that this is just going to print out some additional context inside of the console window. So it turns out that you can do some very interesting things using C 15 unions. I'm definitely excited to test this out in practice. And I'm going to leave one of my open source repos in the description of this video where I reimplemented the entire solution in .NET 11 using C# 15 unions and railway oriented programming. Now, this is taking it a bit to the extreme, but I think it's interesting to see what a codebase leveraging this to the maximum could potentially look like. If you enjoy this video, consider smashing the like button. I would really appreciate it. Thanks a lot for watching and until next time, stay awesome.
Summary
This transcript explores utilizing union types in C# 15 to enforce structured code and improve the result pattern. It specifically references the result pattern, custom outcome and either monads, and concrete error types like apartment not found, overlap, and stay-too-short failures. The practical takeaway is that by defining business outcomes and errors as concrete types within a union, developers can leverage the C# compiler to enforce exhaustive pattern matching and prevent unhandled business rules.