Vogen

Vogen

.NET领域驱动设计的值对象生成器

Vogen是一个面向.NET平台的源代码生成器和分析器,可将原始数据类型转换为表示领域概念的值对象。它通过生成编译时错误来防止创建无效的值对象,同时保持与原始类型相近的性能。Vogen有助于实现领域驱动设计,提高代码的表达力和类型安全性,从而改善软件质量。

Vogen源代码生成器值对象原始类型偏执性能优化Github开源项目
NameOperating SystemStatusHistory
GitHub ActionsUbuntu, Mac & WindowsBuildGitHub Actions Build History

GitHub release GitHub license GitHub issues GitHub issues-closed NuGet Badge

<!--suppress HtmlDeprecatedAttribute --> <p align="center"> <img src="./assets/cavey.png" alt="Picture of caveman holding the number '1'"> </p>

Sparkline

Give a Star! :star:

If you like or are using this project please give it a star. Thanks!

Vogen: cure your Primitive Obsession

Vogen 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.

Documentation

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) { ... }

Note:

int is the default type for value objects, but it is generally a good idea to explicitly declare each type for clarity. Plus, although int is the default, you can - individually or globally - configure them to be other types. See the Configuration section later in the document, but here's some brief examples:

[ValueObject<decimal>] public partial struct AccountBalance { } [ValueObject(typeof(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(typeof(CustomerId)); // error VOG025: Type 'MyVo' 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 have Age age. Age might have validation that it couldn't be negative
  • instead of string postcode - we'd have Postcode postcode. Postcode might 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 Validate that returns a Validation result
  • Any validation that is not Validation.Ok results in a ValueObjectValidationException being 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:

Primitive Obsession is being obsessed with the seemingly convenient way that primitives, such as ints and strings, allow us to represent domain objects and ideas.

It is this:

int customerId = 42

What's wrong with that?

A customer ID likely cannot be fully represented by an int. An int can be negative or zero, but it's unlikely a customer ID can be. So, we have constraints on a customer ID. We can't represent or enforce those constraints on an int.

So, we need some validation to ensure the constraints of a customer ID are met. Because it's in int, we can't be sure if it's been checked beforehand, so we need to check it every time we use it. Because it's a primitive, someone might've changed the value, so even if we're 100% sure we've checked it before, it still might need checking again.

So far, we've used as an example, a customer ID of value 42. In C#, it may come as no surprise that "42 == 42" (I haven't checked that in JavaScript!). But, in our domain, should 42 always equal 42? Probably not if you're comparing a Supplier ID of 42 to a Customer ID of 42! But primitives won't help you here (remember, 42 == 42!).

(42 == 42) // true (SuppliedId.From(42) == SupplierId.From(42)) // true (SuppliedId.From(42) == VendorId.From(42)) // compilation error

But sometimes, we need to denote that a value object isn't valid or has not been set. We don't want anyone outside of the object doing this as it could be used accidentally. It's common to have Unspecified instances, e.g.

public class Person { public Age Age { get; } = Age.Unspecified; }

We can do that with an Instance attribute:

[ValueObject] [Instance("Unspecified", -1)] public readonly partial struct Age { public static Validation Validate(int value) => value > 0 ? Validation.Ok : Validation.Invalid("Must be greater than zero."); }

This generates public static Age Unspecified = new Age(-1);. The constructor is private, so only this type can (deliberately) create invalid instances.

Now, when we use Age, our validation becomes clearer:

public void Process(Person person) { if(person.Age == Age.Unspecified) { // age not specified. } }

We can also specify other instance properties:

[ValueObject(typeof(float))] [Instance("Freezing", 0)] [Instance("Boiling", 100)] public readonly partial struct Celsius { public static Validation Validate(float value) => value >= -273 ? Validation.Ok : Validation.Invalid("Cannot be colder than absolute zero"); }

Configuration

Each value object can have it's own optional configuration. Configuration includes:

  • The underlying type
  • Any 'conversions' (Dapper, System.Text.Json, Newtonsoft.Json, etc.) - see the Integrations page in the wiki for more information
  • The type of the exception that is thrown when validation fails

If any of those above are not specified, then global configuration is inferred. It looks like this:

[assembly: VogenDefaults(underlyingType: typeof(int), conversions: Conversions.Default, throws: typeof(ValueObjectValidationException))]

Those again are optional. If they're not specified, then they are defaulted to:

  • Underlying type = typeof(int)
  • Conversions = Conversions.Default (TypeConverter and System.Text.Json)
  • Validation exception type = typeof(ValueObjectValidationException)

There are several code analysis warnings for invalid configuration, including:

  • when you specify an exception that does not derive from System.Exception
  • when your exception does not have 1 public constructor that takes an int
  • when the combination of conversions does not match an entry

Performance

(to run these yourself: dotnet run -c Release --framework net8.0 -- --job short --filter * in the Vogen.Benchmarks folder)

As mentioned previously, the goal of Vogen is to achieve very similar performance compare to using primitives themselves. Here's a benchmark comparing the use of a validated value object with underlying type of int vs using an int natively (primitively 🤓)

BenchmarkDotNet=v0.13.2, OS=Windows 11 (10.0.22621.1194) AMD Ryzen 9 5950X, 1 CPU, 32 logical and 16 physical cores .NET SDK=7.0.102 [Host] : .NET 7.0.2 (7.0.222.60605), X64 RyuJIT AVX2 ShortRun : .NET 7.0.2 (7.0.222.60605), X64 RyuJIT AVX2 Job=ShortRun IterationCount=3 LaunchCount=1 WarmupCount=3
MethodMeanErrorStdDevRatioRatioSDGen0Allocated
UsingIntNatively14.55 ns1.443 ns0.079 ns1.000.00--
UsingValueObjectStruct14.88 ns3.639 ns0.199 ns1.020.02--

There is no discernible difference between using a native int and a VO struct; both are pretty much the same in terms of speed and memory.

The next most common scenario is using a VO class to represent a native String. These results are:

BenchmarkDotNet=v0.13.2, OS=Windows 11 (10.0.22621.1194) AMD Ryzen 9 5950X, 1 CPU, 32 logical and 16 physical cores .NET SDK=7.0.102 [Host] : .NET 7.0.2 (7.0.222.60605), X64 RyuJIT AVX2 ShortRun : .NET 7.0.2 (7.0.222.60605), X64 RyuJIT AVX2 Job=ShortRun IterationCount=3 LaunchCount=1 WarmupCount=3
MethodMeanErrorStdDevRatioRatioSDGen0AllocatedAlloc Ratio
UsingStringNatively151.8 ns32.191.761.000.000.0153256 B1.00
UsingValueObjectAsStruct184.8 ns12.190.671.220.020.0153256 B1.00

There is a tiny amount of performance overhead, but these measurements are incredibly small. There is no memory overhead.

Serialisation and type conversion

By default, each VO is decorated with a TypeConverter and System.Text.Json (STJ) serializer. There are other converters/serializer for:

编辑推荐精选

Vora

Vora

免费创建高清无水印Sora视频

Vora是一个免费创建高清无水印Sora视频的AI工具

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具使用教程AI营销产品酷表ChatExcelAI智能客服
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

热门AI工具生产力协作转型TraeAI IDE
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

数据安全AI助手热门AI工具AI辅助写作AI论文工具论文写作智能生成大纲
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

热门AI工具AI办公办公工具智能排版AI生成PPT博思AIPPT海量精品模板AI创作
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

iTerms

iTerms

企业专属的AI法律顾问

iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。

SimilarWeb流量提升

SimilarWeb流量提升

稳定高效的流量提升解决方案,助力品牌曝光

稳定高效的流量提升解决方案,助力品牌曝光

Sora2视频免费生成

Sora2视频免费生成

最新版Sora2模型免费使用,一键生成无水印视频

最新版Sora2模型免费使用,一键生成无水印视频

下拉加载更多