From 408e6cd82d05ebe99f75d3abdae6dfea00a5b0f0 Mon Sep 17 00:00:00 2001 From: Alejandro Sanchez Bastida Date: Fri, 15 Aug 2025 11:11:29 +0200 Subject: [PATCH 1/4] Add implicit conversions --- Funzo/Result.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Funzo/Result.cs b/Funzo/Result.cs index 3c87243..14e53b8 100644 --- a/Funzo/Result.cs +++ b/Funzo/Result.cs @@ -29,6 +29,17 @@ private Result(TErr err) : base(err) /// An instance of as a failed operation public static Result Err(TErr err) => new(err); + /// + /// Converts into implicitly + /// + /// Value + public static implicit operator Result(TOk ok) => new(ok); + /// + /// Converts into implicitly + /// + /// Value + public static implicit operator Result(TErr err) => new(err); + /// public override bool Equals(object? obj) { @@ -78,6 +89,12 @@ private Result(TErr err) : base(err) /// An instance of as a failed operation public static Result Err(TErr err) => new(err); + /// + /// Converts into implicitly + /// + /// Value + public static implicit operator Result(TErr err) => new(err); + /// public override bool Equals(object? obj) { From 42a15d568865ffaf042d65cc3b35d0787dbf218f Mon Sep 17 00:00:00 2001 From: Alejandro Sanchez Bastida Date: Fri, 15 Aug 2025 11:12:10 +0200 Subject: [PATCH 2/4] Rename old file --- Funzo/{IResult.cs => IResultBase.cs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Funzo/{IResult.cs => IResultBase.cs} (100%) diff --git a/Funzo/IResult.cs b/Funzo/IResultBase.cs similarity index 100% rename from Funzo/IResult.cs rename to Funzo/IResultBase.cs From 780f248416e32f1bfa162ad1975048fa63fd27fa Mon Sep 17 00:00:00 2001 From: Alejandro Sanchez Bastida Date: Fri, 15 Aug 2025 11:16:43 +0200 Subject: [PATCH 3/4] Remove license acceptance --- Funzo.Serialization/Funzo.Serialization.csproj | 1 - Funzo.SourceGenerators/Funzo.SourceGenerators.csproj | 1 - Funzo/Funzo.csproj | 1 - 3 files changed, 3 deletions(-) diff --git a/Funzo.Serialization/Funzo.Serialization.csproj b/Funzo.Serialization/Funzo.Serialization.csproj index d33e007..3be36f8 100644 --- a/Funzo.Serialization/Funzo.Serialization.csproj +++ b/Funzo.Serialization/Funzo.Serialization.csproj @@ -16,7 +16,6 @@ $(AssemblyVersion) $(AssemblyVersion) LICENSE - True diff --git a/Funzo.SourceGenerators/Funzo.SourceGenerators.csproj b/Funzo.SourceGenerators/Funzo.SourceGenerators.csproj index 5edeb65..c03d77b 100644 --- a/Funzo.SourceGenerators/Funzo.SourceGenerators.csproj +++ b/Funzo.SourceGenerators/Funzo.SourceGenerators.csproj @@ -17,7 +17,6 @@ $(AssemblyVersion) $(AssemblyVersion) LICENSE - True diff --git a/Funzo/Funzo.csproj b/Funzo/Funzo.csproj index d6aebff..aca61b5 100644 --- a/Funzo/Funzo.csproj +++ b/Funzo/Funzo.csproj @@ -16,7 +16,6 @@ $(AssemblyVersion) $(AssemblyVersion) LICENSE - True From ae232cf2a94e409566c5284cb0dd8e77d9303f95 Mon Sep 17 00:00:00 2001 From: Alejandro Sanchez Bastida Date: Fri, 15 Aug 2025 11:52:29 +0200 Subject: [PATCH 4/4] Update readme --- README.md | 84 ++++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 65 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 3b74889..fa539d3 100644 --- a/README.md +++ b/README.md @@ -5,15 +5,20 @@ # Funzo ## Contents + - [Where is this coming from](#where-is-this-coming-from) - [Description](#description) +- [Comparison with other packages](#comparison-with-other-packages) + - [OneOf](#one-of) + - [CSharpFunctionalExtensions](#csharpfunctionalextensions) + - [FluentResults](#fluentresults) - [Usage (recommended way)](#usage-recommended-way) - [Documentation](#documentation) - - [Unit](#unit) - - [Option](#option) - - [Result](#result) - - [ResultBuilder](#resultbuilder) - - [Union](#union) + - [Unit](#unit) + - [Option](#option) + - [Result](#result) + - [ResultBuilder](#resultbuilder) + - [Union](#union) - [Serialization](#serialization) - [Example](#example) - [Further work](#further-work) @@ -21,10 +26,12 @@ - [What's missing (updated after adding union types & source generators)](#whats-missing-updated) ## Where is this coming from + This package was previously called OptionTypes, but given that now more things are being added, I think a new name could fit better. Wanted to make it sound like something functional, so Funzo it is. Sounds fine. Apart from the name, the `Maybe` class was renamed to `Option`. It is more common than `Maybe` so I thought it would be better for people to identify it. I ~~copied a lot of things~~ took inspiration of the work done by [`OneOf`](https://github.com/mcintyre321/OneOf) (specially source generators) but decided to adapt it to my way of doing things: **making everything explicit**. ## Description + _Funzo_ allows the developer to use some classes more commonly used in functional programming for error-proof programming and better type definition. It contains 4 classes: - The `Unit` class represents an empty class. Because functions always return something, `Unit` is the equivalent to `void` @@ -37,8 +44,28 @@ _Funzo_ allows the developer to use some classes more commonly used in functiona - The attributes `ResultAttribute` and `UnionAttribute` allow you to generate types and use them with ease. +## Comparison with other packages + +Here is a small comparison with other popular libraries. Each column identifies if the library has what's described and to what extent. + +- **Result**: A result type with 2 options: OK and ERR. +- **Option**: An option type that can show the absence of value without null. +- **Union**: Allows to create discriminated unions. +- **Source generator**: Has a source generator to create your classes with ease. +- **Type safety**: Exposes methods that can throw exceptions. + +| Library | Result | Option | Union | Source Generator | Type Safety | +| --------------------------------------------------------------------------------------- | ---------------------------------- | ------------------------------------ | ----- | ---------------- | ---------------------------------------------------- | +| [`OneOf`](https://github.com/mcintyre321/OneOf) | NO, but can be created with unions | NO, but can be created with unions | YES | YES | YES | +| [`CSharpFunctionalExtensions`](https://github.com/vkhorikov/CSharpFunctionalExtensions) | YES. Dedicated types | YES. Dedicated types | NO | NO | MIXED. You can skip type safety and get exceptions | +| [`FluentResults`](https://github.com/altmann/FluentResults) | YES. Dedicated types | NO, but can be created with a Result | NO | NO | MIXED. You can skip type checking and get exceptions | +| [`ErrorOr`](https://github.com/amantinband/error-or) | YES. Dedicated types | NO, but can be created with a Result | NO | NO | MIXED. You can skip type safety and get exceptions | +| Funzo | YES. Dedicated types | YES. Dedicated types | YES | YES | YES | + +Please understand that this comparison is done on a feature basis and each library has good things over the others. Just because Funzo has 5 YES does not mean that it is the best. It fulfills everything because it was created with just this 5 things in mind. ## Usage (recommended way) + The best way to approach this package is through source generators. This will allow you to define your types with ease and work on your problems straight away. You will need the `Funzo` and `Funzo.SourceGenerators` packages. For unions, decorate it with the `Union` attribute, supplying the generic parameters you want as possible options. @@ -59,15 +86,16 @@ public partial class ItemCreationError; public partial class ItemCreatedResult; ``` - ## Documentation ### Unit + Unit is a helper type to represent the absence of a return value (think of it as void). Because in functional programming every function returns a value, it is added here for compatibility. ### Option Create a new Option using one of the helper methods (`Option.FromValue`, `Option.Some`, and `Option.None`): + ```Csharp var optionInt = Option.Some(1); var optionFloat = Option.FromValue(12); @@ -76,6 +104,7 @@ var optionString = Option.FromValue(nullableString); ``` Map its content using the `Map` method: + ```Csharp var optionText = await ReadTextFromFile(filePath); @@ -83,6 +112,7 @@ var uppercaseText = optionText.Map(text => text.ToUpper()); ``` You can also map to another `Option` and it will be flatten: + ```Csharp var number = Option.FromValue(1); @@ -91,6 +121,7 @@ var double = number.Map(x => Option.FromValue(x * 2)); ``` If you want to check both options, use the `Match` method: + ```Csharp let user = await GetUser(); @@ -99,12 +130,14 @@ var userName = user.Match(x => x.Name, () => "User not found"); ``` In case you want to provide a fallback value, you can use `ValueOr`: + ```Csharp var optionUserName = await GetUserName(); var userName = optionUserName.ValueOr("Unknown user"); ``` In case you want to do something if there is a value present, you can use the `IsSome` method: + ```Csharp Option optionUser = await GetUser(); @@ -116,17 +149,8 @@ if(!optionUser.IsSome(out User user)) var posts = postService.GetPostsByUserId(user.Id); ``` -You can force the value out using the `Unwrap` method. This approach is **not recommended**: -```Csharp -var optionValue = Option.Some(1); - -var value = optionValue.Unwrap() // 1 +There are also extension methods for `Task>` so you can chain `Map`, `Match` and `ValueOr` to your tasks. -var optionString = Option.None; -optionString.Unwrap(); // throws NullReferenceException -``` - -There are also extension methods for `Task>` so you can chain `Map`, `Match`, `ValueOr`, and `Unwrap` to your tasks. ```Csharp var userBalance = GetUser() // GetUser returns a Task> .Map(user => bankService.GetAccounts(user.Id)) @@ -135,6 +159,7 @@ var userBalance = GetUser() // GetUser returns a Task> ``` In case you want to do something with the value first, you can use the `Inspect` function: + ```Csharp Option maybeUser = GetUser(); @@ -142,21 +167,25 @@ user.Inspect(user => Console.WriteLine($"Retrieved user {user.Name}"); ``` ### Result + To use results, you can use the already existing classes `Result` or `Result`, depending on whether you need an Ok value, or use the source generators (much recommended, see above). You can create an instance using the Ok/Err static methods: + ```Csharp var okResult = Result.Ok(); var errorResult = Result.Err(ProcessError.DatabaseConnection); ``` You can map the ok value or err value using `Map` and `MapErr` methods: + ```Csharp var okResult = Result.Ok(3).Map(x => x*2)); // Ok(6) var errResult = Result.Err("failure").MapErr(x => x.ToUpper()); // Err("FAILURE") ``` To provide handlers for both cases, which should be the normal usage, use the `Match` method: + ```Csharp var result = await CreateUser(); @@ -169,6 +198,7 @@ result.Match( ``` Sometimes you only want to know if an operation has completed successfully to get the ok value. You can use the `AsOk` method: + ```Csharp var parsingResult = ParseLines(path); @@ -178,6 +208,7 @@ Console.WriteLine($"Parsed {linesParsed} lines"); ``` In order to get early returns when needed, there is an `IsErr` method: + ```Csharp Result userCreationResult = await CreateUser(userPayload); @@ -188,7 +219,7 @@ if (userCreationResult.IsErr(out User user, out string error)) var userRoleResult = await AssignRoles(user, Roles.Admin); -if (userRoleResult.IsErr(out var roleError)) +if (userRoleResult.IsErr(out var roleError)) { return Result.Err(UserCreationError.CannotAssignRole); } @@ -197,6 +228,7 @@ emailService.NotifyUser(user.Email); ``` As with `Option`, there are some extensions in Task to be able to chain methods: + ```Csharp public async IResult Post([FromBody] UserPayload payload) => await CreateUser(payload).Match( @@ -210,9 +242,11 @@ public async IResult Post([FromBody] UserPayload payload) Same as `Option`, we have 2 methods: `Inspect` and `InspectErr` (and their async variants) in case you want to do something with the values without actually changing anything. ### ResultBuilder + Created by using the static method `For`, lets you map different exceptions to errors, allowing you to migrate from an exception based approach to a result based approach. So you can move from this: + ```Csharp public async Task Main() { @@ -250,6 +284,7 @@ public Task ReserveTable(int userId, DateTime reservationDate) ``` To this: + ```Csharp public async Task Main() { @@ -270,6 +305,7 @@ public partial class ReservationError; In this way, you can refactor safely and remove exceptions one by one, making all your methods explicit about how they can fail so the developer can handle it. ### Union + Unions represent a variable that can be of several different types. At the moment, there are only unions for 5 generic types max. This was on purpose, as it usually more than 5 means you need a refactor to group some of them (at least in my opinion). If you need more, feel free to use the `Funzo.Generator` project and change the ordinality to whatever you need. You can create an instance by using the constructor or by implicitly converting from it: @@ -292,6 +328,7 @@ if (union.Is(out var text)) ``` If you want to do different actions depending on the inner value, you can use the `Switch` or the `Match` methods: + ```Csharp Union union = DateTime.UtcNow; @@ -309,11 +346,15 @@ union.Switch( Unions in this package don't have a `.Value` property and they will never have. ## Serialization + The package `Funzo.Serialization` holds the `JsonConverterFactory` classes needed to work with `System.Text.Json`. At the moment, `Option` serializes to: + ```JSON { "HasValue": bool, "Value": *whatever* } ``` + and `Result` to: + ```JSON { "IsOk": true, "Ok": *whatever* } or @@ -321,6 +362,7 @@ or ``` `Union` serializes as an object with 2 properties: `tag` and `value`: + ```chsarp [Union] public partial class MyUnion ; @@ -330,18 +372,22 @@ public class MyClass public MyUnion Union { get; set; } = new MyUnion(DateTime.UtcNow); } ``` + ```JSON {"Union":{"tag":"DateTime","value":"2025-07-12T13:34:57.6941483Z"}} ``` ## Example + There is a working example of a payment system under `Funzo.Example`. Feel free to take a look at how the code will look after using it. ## Design philosophy + The idea behind this small package was to provide `Option`/`Result` monads that work idiomatically with C#, whithout losing the essence of them. -In order to achieve this, an approach of *Explicit better than implicit* was used: +In order to achieve this, an approach of _Explicit better than implicit_ was used: + - When working with `Option`, minimize the posibility of `NullReferenceException` by limiting the options to get the value out, enforcing the developer to handle all the cases. - When working with `Result`, minimize the risk of unforseen consequences (λ) by encouraging to use the `Match` statement. - Unions don't have the possibility of getting the value explicitly, forcing the developer to use the `Is` method or `Switch`/`Match` -- Encourage the usage of Error values, let it be records with some payload or enums, that provide useful information and force the developer to take action for each one of them. By being explicit in what kind of errors can pop out, the developer is forced to handle all the cases than can go wrong and not rely on catch blocks. \ No newline at end of file +- Encourage the usage of Error values, let it be records with some payload or enums, that provide useful information and force the developer to take action for each one of them. By being explicit in what kind of errors can pop out, the developer is forced to handle all the cases than can go wrong and not rely on catch blocks.