Jacobi.ValueObject
1.3.0
dotnet add package Jacobi.ValueObject --version 1.3.0
NuGet\Install-Package Jacobi.ValueObject -Version 1.3.0
<PackageReference Include="Jacobi.ValueObject" Version="1.3.0" />
<PackageVersion Include="Jacobi.ValueObject" Version="1.3.0" />
<PackageReference Include="Jacobi.ValueObject" />
paket add Jacobi.ValueObject --version 1.3.0
#r "nuget: Jacobi.ValueObject, 1.3.0"
#:package Jacobi.ValueObject@1.3.0
#addin nuget:?package=Jacobi.ValueObject&version=1.3.0
#tool nuget:?package=Jacobi.ValueObject&version=1.3.0
Value Object
Read more on what a Value Object is here (wikipedia).
The assumption in the implementation is:
- A ValueObject is immutable. The code generation adds the
readonlymodifier (so you don't have to). - A ValueObject is compared by content/value - not by reference. Basic
structbehavior in dotnet. - A valid ValueObject never contains a value of
null. So do not specify nullable types as 'datatype'.
Usage
Add a (package) reference to
Jacobi.ValueObject.
using Jacobi.ValueObject;
The library distinguishes between two types of value objects:
ValueObject(Attribute)that contains a single value.MultiValueObject(Attribute)that contains multiple values.
Both the ValueObjectAttribte and MultiValueObjectAttribute work on both partial struct and partial record struct declarations.
partial struct: TheIEquatable<ValueObject>interface is automatically added and implemented.partial record struct: TheIEquatable<ValueObject>interface is added and implemented by the compiler (because record).
Some attribute syntax examples:
// single value
[ValueObject<Guid>]
public partial record struct ProductId;
[ValueObject(typeof(Guid))]
public partial struct ProductId;
// multi value
[MultiValueObject]
public partial struct Product
{
public partial Guid Id { get; }
public partial string Name { get; }
}
We call the
Guidthe 'datatype' and theProductId(orProduct) the 'ValueObject'.
Minimal effort:
[ValueObject<Guid>]
public partial struct ProductId;
...
var prodId = new ProductId(Guid.NewGuid());
[MultiValueObject]
public partial struct Product
{
public partial Guid Id { get; }
public partial string Name { get; }
}
...
var prod = new Product(Guid.NewGuid(), "Product");
Using Options to manage what code (support) is generated.
[ValueObject<Guid>(ValueObjectOptions.Parsable)]
public partial record struct ProductId;
...
var prodId = ProductId.Parse("<guid>", null); // no format provider
Note that the
MultiValueObjectonly supports a few options.
[MultiValueObject(MultiValueObjectOptions.Deconstruct | MultiValueObjectOptions.Constructor)]
public partial struct Product
{
public partial Guid Id { get; }
public partial string Name { get; }
}
...
(var id, var name) = new Product(Guid.NewGuid(), "Product");
This also works:
[ValueObject<Guid>(ValueObjectOptions.ImplicitFrom)]
public partial struct ProductId;
[MultiValueObject]
public partial record struct Product
{
public partial ProductId Id {get;}
public partial string Name {get;}
}
...
// can construct a ProductId from a Guid because of ImplicitFrom option.
var vo = new Product(Guid.NewGuid(), "name");
Implement validation by providing a static bool IsValid(<datatype> value) method.
You determine the accessibility (public, internal, private).
[ValueObject<Guid>]
public partial record struct ProductId
{
public static bool IsValid(Guid id) => id != Guid.Empty;
}
...
var prodId = new ProductId(Guid.Empty); // <- will throw
[MultiValueObject]
public partial record struct Product
{
public partial Guid Id { get; }
public partial string Name { get; }
public static bool IsValid(Guid id, string name) => id != Guid.Empty && !String.IsNullOrEmpty(name);
}
...
var prod = new Product(Guid.Empty, ""); // <- will throw
Options
Specify options in the ValueObjectAttribute or MultiValueObjectAttribute. Here are the variants:
[ValueObject<Guid>(ValueObjectOptions.Parsable)]
public partial record struct ProductId;
[ValueObject<Guid>(Options = ValueObjectOptions.Parsable)]
public partial record struct ProductId;
[ValueObject(typeof(Guid), Options = ValueObjectOptions.Parsable)]
public partial record struct ProductId;
[MultiValueObject(MultiValueObjectOptions.Deconstruct]
public partial record struct Product
{ ... }
The 'Single' column indicates support for the ValueObjectAttribute options (Yes/No).
The 'Multi' column indicates support for the MultiValueObjectAttribute options (Yes/No).
| Option | Single | Multi | Description |
|---|---|---|---|
| Constructor | Y | Y | Makes the value-constructor public. This option is default if none are specified. |
| ImpicitFrom | Y | N | Adds an implicit assignment operator that allows assigning the <datatype> value to a new instance of the ValueObject. Additionally an implementation for the IEquatable<datatype> interface will also be generated. |
| ImplicitAs | Y | N | Adds an implicit assignment operator that allows assigning the ValueObject to a <datatype> variable. Additionally an implementation for the IEquatable<datatype> interface will also be generated. |
| ExplicitFrom | Y | Y | Adds a static factory method From that construct a new ValueObject instance from a specified <datatype> value. |
| ToString | Y | N | Overrides the record struct dotnet implementation to return the ValueObject.Value as string. |
| Comparable | Y | N | Implements the IComparable<ValueObject> interface to compare between ValueObject instances. If ImplicitFrom and/or ImplictAs options are also active, an implementation for IComparable<datatype> is also generated. |
| Parsable | Y | N | Implements the IParsable<ValueObject> and ISpanParsable<ValueObject> interfaces to provide Parse and TryParse methods. Note that this option cannot be used in combination with a <datatype> of string (System.String). |
| Deconstruct | N | Y | Allows deconstruction syntax ((var id, var name) = prod;) for MultiValueObject instances. |
As an alternative for ValueObjectAttribute there is also an option to declare the interfaces explicitly and forgo specifying options.
The folowing interfaces are supported:
| Interface | Description |
|---|---|
IEquatable<datatype> |
Implements the IEquatable<T> interface for the datatype, as you get with the implicit-options. |
IComparable<ValueObject> |
Implements the IComparable<T> interface for the ValueObject, as if the Comparable option was specified. |
IComparable<datatype> |
Implements the IComparable<T> interface for the datatype, as if the Comparable option was specified together with one of the implicit-options. |
IParsable<ValueObject> |
Implements the IParsable<T> interface for the ValueObject (but not ISpanParsable<T>), as if the Parsable option was specified. |
ISpanParsable<ValueObject> |
Implements the ISpanParsable<T> interface for the ValueObject (including IParsable<T>), as if the Parsable option was specified. |
Note that IEquatable<ValueObject> is always present. Either generated by the compiler when using a record struct or by Jacobi.ValueObject when using struct.
Methods
Implement a static bool IsValid(<datatype>) method in your ValueObject for ValueObjectAttribute or static bool IsValid(<property datatypes in order>) for MultiValueObjectAttribute and it will be detected and used when constructing new instances.
[ValueObject<Guid>]
public partial struct ProductId
{
// public, internal or private - you decide
public static bool IsValid(Guid id) => id != Guid.Empty;
}
[MultiValueObject]
public partial struct Product
{
public partial Guid Id { get; }
public partial string Name { get; }
// public, internal or private - you decide
public static bool IsValid(Guid id, string name) => id != Guid.Empty && !String.IsNullOrEmpty(name);
}
Note that if a static bool IsValid() method is detected an extra (static) method Try is generated that uses the IsValid to optionally create a new instance of the ValueObject.
[ValueObject<Guid>]
public partial struct ProductId
{
public static bool IsValid(Guid id) => id != Guid.Empty;
}
...
if (ProductId.Try(Guid.NewGuid(), out var valueObject))
{
// use 'valueObject' here
}
This works similarly in the case of MultiValueObjectAttribute.
Declare a public static partial ValueObject From(<datatype>); partial method (no implementation) for ValueObjectAttribute or public static partial MultiValueObject From(<property datatypes in order>) for MultiValueObjectAttribute in your ValueObject and it will be detected and implemented similar to specifying the ExplicitFrom option.
[ValueObject<Guid>]
public partial record struct ProductId
{
public static partial ProductId From(Guid id);
}
Exceptions
The Jacobi.ValueObject.ValueObjectException is throw in these circumstances.
- The default (parameterless) constructor of the ValueObject is called.
- The
Valueor custom properties are accessed while the instance of the ValueObject was not correctly initialized. - If the ValueObject implements the
IsValidstatic method and the value(s) fails the test.
Project File
To see the generated source files for the value objects, add to your .csproj project file:
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
</PropertyGroup>
You'll find the generated Xxxx_ValueObject.g.cs source code files in the <Project>\obj\Debug\net8.0\generated\Jacobi.ValueObject.Generator\Jacobi.ValueObject.Generator.(Multi)Generator\ folders (assuming a Debug build of net8.0).
Compiler Errors
| Code | Multi | Error |
|---|---|---|
| VO001 | Y | You have declare a ValueObject in the global namespace. It is mandatory to declare your ValueObjects inside a namespace. |
| VO002 | N | You did [ValueObject(null)] - It cannot work without a datatype. |
| VO003 | N | You used the Parsable option on a ValueObject with the string/Systsem.String datatype. |
| VO004 | Y | You used set or init in you property declarations of the multi-value object. Properties must be readon-only. |
| VO005 | Y | You specified ref on the property type. You cannot use `ref'. |
CSXXXX Compiler errors caused by you not following the rules 😃
- Do not specify a default constructor. So do NOT do this:
public partial record struct ProductId() - Do not use the
ToStringoption and also implement astring ToString()override in your ValueObject. - You did not specify the
IsValid'properties' in the correct order for aMultiValueObjectAttribute. - Multi: IsValid() parameter errors. You probably mixed up the order of the parameters.
Generated Code
Here is an example of the code that will be generated for a ValueObjectAttribute when all options and features are active.
Note that there are slight differences between a struct and a record struct -most notably IEquatable<ValueObject>.
The comments in the code (normally not generated) serve as a short explanation for the sets of members.
The YourNamespace and YourValueObject symbols are the namespace and value object type names you have chosen. The 'datatype' in this sample is int.
namespace YourNamespace
{
[System.CodeDom.Compiler.GeneratedCode("Jacobi.ValueObject.Generator", "1.1.0.0")]
[System.Diagnostics.DebuggerDisplay("Value = {Value}")]
readonly partial struct YourValueObject : System.IEquatable<YourValueObject>, System.IEquatable<int>, System.IComparable<YourValueObject>, System.IComparable<int>, System.IParsable<ValObj>, System.ISpanParsable<ValObj>
{
public YourValueObject() => throw new Jacobi.ValueObject.ValueObjectException("Do not call the default constructor for ValueObject 'YourValueObject'.");
private readonly int? _value;
public int Value => _value ?? throw new Jacobi.ValueObject.ValueObjectException("ValueObject 'YourValueObject' was not initialized with a valid value.");
// Constructor (public)
public YourValueObject(int value) => _value = value;
// Constructor when 'static bool IsValid(int value)' is detected
public YourValueObject(int value) { if (YourValueObject.IsValid(value)) _value = value; else throw new Jacobi.ValueObject.ValueObjectException($"Validation Failed. The value '{value}' is not valid for Value Object 'YourValueObject'."); }
public static bool Try(int value, out YourValueObject valueObject) { if (YourValueObject.IsValid(value)) { valueObject = new(value); return true; } valueObject = default; return false; }
// implicit
public static implicit operator int(YourValueObject value) => value.Value;
public static implicit operator YourValueObject(int value) => new(value);
// explicit
public static YourValueObject From(int value) => new(value);
public override string ToString() => Value.ToString();
// IEquatable<ValueObject> (only for struct)
public bool Equals(ValObj value) => Value.Equals(value.Value);
public static bool operator ==(ValObj valueObject, ValObj value) => valueObject.Equals(value);
public static bool operator !=(ValObj valueObject, ValObj value) => !valueObject.Equals(value);
// IEquatable<datatype> (implicit)
public bool Equals(int value) => Value.Equals(value);
public static bool operator ==(YourValueObject valueObject, int value) => valueObject.Equals(value);
public static bool operator !=(YourValueObject valueObject, int value) => !valueObject.Equals(value);
// IComparable<ValueObject>
public int CompareTo(YourValueObject value) => Value.CompareTo(value.Value);
public static bool operator >(YourValueObject value1, YourValueObject value2) => value1.CompareTo(value2) > 0;
public static bool operator <(YourValueObject value1, YourValueObject value2) => value1.CompareTo(value2) < 0;
public static bool operator >=(YourValueObject value1, YourValueObject value2) => value1.CompareTo(value2) >= 0;
public static bool operator <=(YourValueObject value1, YourValueObject value2) => value1.CompareTo(value2) <= 0;
// IComparable<datatype> (implicit)
public int CompareTo(int value) => Value.CompareTo(value);
public static bool operator >(YourValueObject value1, int value2) => value1.CompareTo(value2) > 0;
public static bool operator <(YourValueObject value1, int value2) => value1.CompareTo(value2) < 0;
public static bool operator >=(YourValueObject value1, int value2) => value1.CompareTo(value2) >= 0;
public static bool operator <=(YourValueObject value1, int value2) => value1.CompareTo(value2) <= 0;
// IParsable<ValueObject>
public static YourValueObject Parse(string? str, System.IFormatProvider? formatProvider) => new(int.Parse(str, formatProvider));
public static bool TryParse(string? str, System.IFormatProvider? formatProvider, out YourValueObject result)
{
if (int.TryParse(str, formatProvider, out var dtResult)) { result = new (dtResult); return true; }
result = default; return false;
}
// ISpanParsable<ValueObject>
public static YourValueObject Parse(System.ReadOnlySpan<char> str, System.IFormatProvider? formatProvider) => new(int.Parse(str, formatProvider));
public static bool TryParse(System.ReadOnlySpan<char> str, System.IFormatProvider? formatProvider, out YourValueObject result)
{
if (int.TryParse(str, formatProvider, out var dtResult)) { result = new (dtResult); return true; }
result = default; return false;
}
}
}
Unsupported
- Json Serialization (System.Text.Json or Newtonsoft.Json)
- AspNet (TypeConvertor)
- EFcore (ValueConvertor)
For now, you have to write these yourself.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.