Vogen
A semi-opinionated library which is a source generator and a code analyser. It Source generates Value Objects
Install / Use
/learn @SteveDunn/VogenREADME
Give a Star! :star:
If you like or are using this project please give it a star. Thanks!
Vogen: cure your Primitive Obsession
Vogen (pronounced "Voh Jen") is a .NET Source Generator and analyzer. It turns your primitives (ints, decimals etc.) into value objects that represent domain concepts (CustomerId, AccountBalance etc.)
It adds new C# compilation errors to help stop the creation of invalid value objects.
This readme covers some of the functionality. Please see the Wiki for more detailed information, such as getting started, tutorials, and how-tos.
Overview
The source generator generates strongly typed domain concepts. You provide this:
[ValueObject<int>]
public partial struct CustomerId;
... and Vogen generates source similar to this:
public partial struct CustomerId :
System.IEquatable<CustomerId>,
System.IComparable<CustomerId>, System.IComparable
{
private readonly int _value;
public readonly int Value => _value;
public CustomerId() {
throw new Vogen.ValueObjectValidationException(
"Validation skipped by attempting to use the default constructor...");
}
private CustomerId(int value) => _value = value;
public static CustomerId From(int value) {
CustomerId instance = new CustomerId(value);
return instance;
}
public readonly bool Equals(CustomerId other) ...
public readonly bool Equals(int primitive) ...
public readonly override bool Equals(object obj) ...
public static bool operator ==(CustomerId left, CustomerId right) ...
public static bool operator !=(CustomerId left, CustomerId right) ...
public static bool operator ==(CustomerId left, int right) ...
public static bool operator !=(CustomerId left, int right) ...
public static bool operator ==(int left, CustomerId right) ...
public static bool operator !=(int left, CustomerId right) ...
public readonly override int GetHashCode() ...
public readonly override string ToString() ...
}
You then use CustomerId instead of int in your domain in the full knowledge that it is valid and safe to use:
CustomerId customerId = CustomerId.From(123);
SendInvoice(customerId);
...
public void SendInvoice(CustomerId customerId) { ... }
(you'll see the default public constructor is created, but the analyzer stops you from using it, as described in a bit...)
int is the default type for value objects. It is generally a good idea to explicitly declare each type
for clarity. You can also - individually or globally - configure them to be
other types. See the Configuration section later in the document.
Here's some other examples:
[ValueObject<decimal>]
public partial struct AccountBalance;
[ValueObject<string>]
public partial class LegalEntityName;
The main goal of Vogen is to ensure the validity of your value objects, the code analyser helps you to avoid mistakes which might leave you with uninitialized value objects in your domain.
It does this by adding new constraints in the form of new C# compilation errors. There are a few ways you could end up with uninitialized value objects. One way is by giving your type constructors. Providing your own constructors could mean that you forget to set a value, so Vogen doesn't allow you to have user defined constructors:
[ValueObject]
public partial struct CustomerId
{
// Vogen deliberately generates this so that you can't create your own:
// error CS0111: Type 'CustomerId' already defines a member called 'CustomerId'
// with the same parameter type
public CustomerId() { }
// error VOG008: Cannot have user defined constructors,
// please use the From method for creation.
public CustomerId(int value) { }
}
In addition, Vogen will spot issues when creating or consuming value objects:
// catches object creation expressions
var c = new CustomerId(); // error VOG010: Type 'CustomerId' cannot be constructed with 'new' as it is prohibited
CustomerId c = default; // error VOG009: Type 'CustomerId' cannot be constructed with default as it is prohibited.
var c = default(CustomerId); // error VOG009: Type 'CustomerId' cannot be constructed with default as it is prohibited.
var c = GetCustomerId(); // error VOG010: Type 'CustomerId' cannot be constructed with 'new' as it is prohibited
var c = Activator.CreateInstance<CustomerId>(); // error VOG025: Type 'CustomerId' cannot be constructed via Reflection as it is prohibited.
var c = Activator.CreateInstance(<CustomerId>); // error VOG025: Type 'CustomerId' cannot be constructed via Reflection as it is prohibited.
// catches lambda expressions
Func<CustomerId> f = () => default; // error VOG009: Type 'CustomerId' cannot be constructed with default as it is prohibited.
// catches method / local function return expressions
CustomerId GetCustomerId() => default; // error VOG009: Type 'CustomerId' cannot be constructed with default as it is prohibited.
CustomerId GetCustomerId() => new CustomerId(); // error VOG010: Type 'CustomerId' cannot be constructed with 'new' as it is prohibited
CustomerId GetCustomerId() => new(); // error VOG010: Type 'CustomerId' cannot be constructed with 'new' as it is prohibited
// catches argument / parameter expressions
Task<CustomerId> t = Task.FromResult<CustomerId>(new()); // error VOG010: Type 'CustomerId' cannot be constructed with 'new' as it is prohibited
void Process(CustomerId customerId = default) { } // error VOG009: Type 'CustomerId' cannot be constructed with default as it is prohibited.
One of the main goals of this project is to achieve almost the same speed and memory performance as using primitives directly.
Put another way, if your decimal primitive represents an Account Balance, then there is extremely low overhead of
using an AccountBalance value object instead. Please see the performance metrics below.
Installation
Vogen is a Nuget package. Install it with:
dotnet add package Vogen
When added to your project, the source generator generates the wrappers for your primitives and the code analyser will let you know if you try to create invalid value objects.
Usage
Think about your domain concepts and how you use primitives to represent them, e.g. instead of this:
public void HandlePayment(int customerId, int accountId, decimal paymentAmount)
... have this:
public void HandlePayment(CustomerId customerId, AccountId accountId, PaymentAmount paymentAmount)
It's as simple as creating types like this:
[ValueObject]
public partial struct CustomerId;
[ValueObject]
public partial struct AccountId;
[ValueObject<decimal>]
public partial struct PaymentAmount;
More on Primitive Obsession
The source generator generates value objects. value objects help combat Primitive Obsession by wrapping simple primitives such as int, string, double etc. in a strongly-typed type.
Primitive Obsession (AKA StringlyTyped) means being obsessed with primitives. It is a Code Smell that degrades the quality of software.
"Primitive Obsession is using primitive data types to represent domain ideas" #
Some examples:
- instead of
int age- we'd haveAge age.Agemight have validation that it couldn't be negative - instead of
string postcode- we'd havePostcode postcode.Postcodemight have validation on the format of the text
The source generator is opinionated. The opinions help ensure consistency. The opinions are:
- A value object (VO) is constructed via a factory method named
From, e.g.Age.From(12) - A VO is equatable (
Age.From(12) == Age.From(12)) - A VO, if validated, is validated with a static method named
Validatethat returns aValidationresult - Any validation that is not
Validation.Okresults in aValueObjectValidationExceptionbeing thrown
It is common to represent domain ideas as primitives, but primitives might not be able to fully describe the domain idea.
To use value objects instead of primitives, we simply swap code like this:
public class CustomerInfo {
private int _id;
public CustomerInfo(int id) => _id = id;
}
.. to this:
public class CustomerInfo {
private CustomerId _id;
public CustomerInfo(CustomerId id) => _id = id;
}
Tell me more about the Code Smell
There's a blog post here that describes it, but to summarise:
