Name | Operating System | Status | History |
---|---|---|---|
GitHub Actions | Ubuntu, Mac & Windows |
If you like or are using this project please give it a star. Thanks!
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.
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, althoughint
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.
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.
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 { }
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:
int age
- we'd have Age age
. Age
might have validation that it couldn't be negativestring postcode
- we'd have Postcode postcode
. Postcode
might have validation on the format of the textThe source generator is opinionated. The opinions help ensure consistency. The opinions are:
From
, e.g. Age.From(12)
Age.From(12) == Age.From(12)
)Validate
that returns a Validation
resultValidation.Ok
results in a ValueObjectValidationException
being thrownIt 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; }
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
andstrings
, 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"); }
Each value object can have it's own optional configuration. Configuration includes:
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:
typeof(int)
Conversions.Default
(TypeConverter
and System.Text.Json
)typeof(ValueObjectValidationException)
There are several code analysis warnings for invalid configuration, including:
System.Exception
(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
Method | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Allocated |
---|---|---|---|---|---|---|---|
UsingIntNatively | 14.55 ns | 1.443 ns | 0.079 ns | 1.00 | 0.00 | - | - |
UsingValueObjectStruct | 14.88 ns | 3.639 ns | 0.199 ns | 1.02 | 0.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
Method | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Allocated | Alloc Ratio |
---|---|---|---|---|---|---|---|---|
UsingStringNatively | 151.8 ns | 32.19 | 1.76 | 1.00 | 0.00 | 0.0153 | 256 B | 1.00 |
UsingValueObjectAsStruct | 184.8 ns | 12.19 | 0.67 | 1.22 | 0.02 | 0.0153 | 256 B | 1.00 |
There is a tiny amount of performance overhead, but these measurements are incredibly small. There is no memory overhead.
By default, each VO is decorated with a TypeConverter
and System.Text.Json
(STJ) serializer. There are other converters/serializer for:
字节跳动发布的AI编程神器IDE
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
AI小说写作助手,一站式润色、改写、扩写
蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率 。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生 活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧 美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供 丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
AI助力,做PPT更简单!
咔片是一款轻量化在线演示设计工具,借助 AI 技术 ,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。
选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。
专业的AI公文写作平台,公文写作神器
AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号