Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Funzo.Serialization/Funzo.Serialization.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
<AssemblyVersion>$(AssemblyVersion)</AssemblyVersion>
<FileVersion>$(AssemblyVersion)</FileVersion>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
<Version></Version>
</PropertyGroup>

Expand Down
1 change: 0 additions & 1 deletion Funzo.SourceGenerators/Funzo.SourceGenerators.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
<AssemblyVersion>$(AssemblyVersion)</AssemblyVersion>
<FileVersion>$(AssemblyVersion)</FileVersion>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
<Version></Version>
</PropertyGroup>

Expand Down
1 change: 0 additions & 1 deletion Funzo/Funzo.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
<AssemblyVersion>$(AssemblyVersion)</AssemblyVersion>
<FileVersion>$(AssemblyVersion)</FileVersion>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
<Version></Version>
</PropertyGroup>

Expand Down
File renamed without changes.
17 changes: 17 additions & 0 deletions Funzo/Result.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ private Result(TErr err) : base(err)
/// <returns>An instance of <see cref="Result{TOk, TErr}"/> as a failed operation</returns>
public static Result<TOk, TErr> Err(TErr err) => new(err);

/// <summary>
/// Converts <typeparamref name="TOk"/> into <see cref="Result{TOk, TErr}" /> implicitly
/// </summary>
/// <param name="ok">Value</param>
public static implicit operator Result<TOk, TErr>(TOk ok) => new(ok);
/// <summary>
/// Converts <typeparamref name="TErr"/> into <see cref="Result{TOk, TErr}" /> implicitly
/// </summary>
/// <param name="err">Value</param>
public static implicit operator Result<TOk, TErr>(TErr err) => new(err);

/// <inheritdoc />
public override bool Equals(object? obj)
{
Expand Down Expand Up @@ -78,6 +89,12 @@ private Result(TErr err) : base(err)
/// <returns>An instance of <see cref="Result{TErr}"/> as a failed operation</returns>
public static Result<TErr> Err(TErr err) => new(err);

/// <summary>
/// Converts <typeparamref name="TErr"/> into <see cref="Result{TErr}" /> implicitly
/// </summary>
/// <param name="err">Value</param>
public static implicit operator Result<TErr>(TErr err) => new(err);

/// <inheritdoc />
public override bool Equals(object? obj)
{
Expand Down
84 changes: 65 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,33 @@
# 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)
- [Design Philosophy](#design-philosophy)
- [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<T>` class was renamed to `Option<T>`. It is more common than `Maybe<T>` 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`
Expand All @@ -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.
Expand All @@ -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);
Expand All @@ -76,13 +104,15 @@ var optionString = Option.FromValue(nullableString);
```

Map its content using the `Map` method:

```Csharp
var optionText = await ReadTextFromFile(filePath);

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);

Expand All @@ -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();

Expand All @@ -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<User> optionUser = await GetUser();

Expand All @@ -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<Option<T>>` so you can chain `Map`, `Match` and `ValueOr` to your tasks.

var optionString = Option<string>.None;
optionString.Unwrap(); // throws NullReferenceException
```

There are also extension methods for `Task<Option<T>>` so you can chain `Map`, `Match`, `ValueOr`, and `Unwrap` to your tasks.
```Csharp
var userBalance = GetUser() // GetUser returns a Task<Option<User>>
.Map(user => bankService.GetAccounts(user.Id))
Expand All @@ -135,28 +159,33 @@ var userBalance = GetUser() // GetUser returns a Task<Option<User>>
```

In case you want to do something with the value first, you can use the `Inspect` function:

```Csharp
Option<User> maybeUser = GetUser();

user.Inspect(user => Console.WriteLine($"Retrieved user {user.Name}");
```

### Result

To use results, you can use the already existing classes `Result<TOk, TErr>` or `Result<TErr>`, 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<ProcessError>.Ok();
var errorResult = Result<Unit, ProcessError>.Err(ProcessError.DatabaseConnection);
```

You can map the ok value or err value using `Map` and `MapErr` methods:

```Csharp
var okResult = Result<int, Exception>.Ok(3).Map(x => x*2)); // Ok(6)
var errResult = Result<string>.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();

Expand All @@ -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);

Expand All @@ -178,6 +208,7 @@ Console.WriteLine($"Parsed {linesParsed} lines");
```

In order to get early returns when needed, there is an `IsErr` method:

```Csharp
Result<User, string> userCreationResult = await CreateUser(userPayload);

Expand All @@ -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<Unit, UserCreationError>.Err(UserCreationError.CannotAssignRole);
}
Expand All @@ -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<IResult>(
Expand All @@ -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()
{
Expand Down Expand Up @@ -250,6 +284,7 @@ public Task<int> ReserveTable(int userId, DateTime reservationDate)
```

To this:

```Csharp
public async Task Main()
{
Expand All @@ -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:
Expand All @@ -292,6 +328,7 @@ if (union.Is<string>(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<int, string, DateTime> union = DateTime.UtcNow;

Expand All @@ -309,18 +346,23 @@ 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
{ "IsOk": false, "Err": *whatever* }
```

`Union` serializes as an object with 2 properties: `tag` and `value`:

```chsarp
[Union<int, string, DateTime>]
public partial class MyUnion ;
Expand All @@ -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.
- 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.
Loading