Git Product home page Git Product logo

transparentvalueobjects's Introduction

TransparentValueObjects

Source generator and analyzer to create Value Objects.

Example

using System;
using TransparentValueObjects;

[ValueObject<Guid>]
public readonly partial struct MyId { }

The attribute ValueObject<TInnerValue> will generate a partial implementation of this readonly struct with the following defaults:

  • A public readonly TInnerValue Value field.
  • A public static T From(TInnerValue innerValue) method that uses the private constructor.
  • A private constructor used by the From method.
  • A public constructor marked as Obsolete with error: true that will throw an exception if called (this behavior can be overwritten using Augments).
  • GetHashCode and ToString implementations that call the same methods on the inner value.
  • Equality methods: object.Equals, IEquatable<T> and IEquatable<TInnerValue>.
    • == and != operators.
    • Additional Equals method with IEqualityComparer<TInnerValue> parameter.
  • Explicit cast operators.
  • IComparable<T> and IComparable<TInnerValue> if TInnerValue implements IComparable<TInnerValue>.
    • <, <=, > and >= operators.
  • For Guid only: NewId method that calls From(Guid.NewGuid()).

You can check the test files to view the generated output.

Augments

The biggest selling point of this project is the augment feature. You can use the IAugmentWith interface to "augment" your Value Object with additional functionality:

using System;
using TransparentValueObjects;

[ValueObject<Guid>]
public readonly partial struct SampleGuidValueObject : IAugmentWith<
    DefaultValueAugment,
    JsonAugment,
    EfCoreAugment>
{
    /// <inheritdoc/>
    public static SampleGuidValueObject DefaultValue => From(Guid.Empty);
}

The following augments are currently available:

Default Value

Augments the Value Object with the IDefaultValue interface that has a static member DefaultValue:

public static abstract TValueObject DefaultValue { get; }
using System;
using TransparentValueObjects;

[ValueObject<Guid>]
public readonly partial struct SampleGuidValueObject : IAugmentWith<DefaultValueAugment>
{
    /// <inheritdoc/>
    public static SampleGuidValueObject DefaultValue => From(Guid.Empty);
}

You have to implement the DefaultValue member when using this augment. The public constructor will now also be available:

public SampleGuidValueObject()
{
    Value = DefaultValue.Value;
}

Default Equality Comparer

Augments the Value Object with the IDefaultEqualityComparer interface that has a static member InnerValueDefaultEqualityComparer:

public static abstract IEqualityComparer<TInnerValue> InnerValueDefaultEqualityComparer { get; }
[ValueObject<string>]
public readonly partial struct SampleStringValueObject : IAugmentWith<DefaultEqualityComparerAugment>
{
    /// <inheritdoc/>
    public static IEqualityComparer<string> InnerValueDefaultEqualityComparer => StringComparer.OrdinalIgnoreCase;
}

This default equality comparer will be used by the following methods:

public bool Equals(SampleStringValueObject other) => Equals(other.Value);

public bool Equals(string? other) => InnerValueDefaultEqualityComparer.Equals(Value, other);

public override int GetHashCode() => InnerValueDefaultEqualityComparer.GetHashCode(Value);

This augment is especially great for strings if you want to always use the case-insensitive equality comparer.

Json Augment

Augments the Value Object with a JSON converter:

[ValueObject<string>]
public readonly partial struct SampleStringValueObject : IAugmentWith<JsonAugment> { }

Only System.Text.Json is currently supported! See #11 for Newtonsoft.Json support.

[JsonConverter(typeof(JsonConverter))]
readonly partial struct SampleStringValueObject
{
    public class JsonConverter : JsonConverter<SampleStringValueObject> { /* omitted */ }
}

The JsonConverterAttribute will be added to the Value Object, meaning that you can use the added converter without needing to manually add it to the JSON options.

The source generator will create a custom converter for the following types:

  • string
  • Guid
  • Int16
  • Int32
  • Int64
  • UInt16
  • UInt32
  • UInt64

All other types will use a fallback converter that fetches an existing converter for TInnerValue.

Note: If the inner value type is a reference type, like string, then you will need to also augment the Value Object with the DefaultValueAugment.

EF Core Augment

Augments the Value Object with a ValueConverter<T, TInnerValue> and ValueComparer<T>:

[ValueObject<string>]
public readonly partial struct SampleStringValueObject : IAugmentWith<EfCoreAugment> { }
public class EfCoreValueConverter : ValueConverter<SampleStringValueObject, string>
{
    public EfCoreValueConverter() : this(mappingHints: null) { }

    public EfCoreValueConverter(ConverterMappingHints? mappingHints = null) : base(
        static value => value.Value,
        static innerValue => From(innerValue),
        mappingHints
    ) { }
}

public class EfCoreValueComparer : ValueComparer<SampleStringValueObject>
{
    public EfCoreValueComparer() : base(
        static (left, right) => left.Equals(right),
        static value => value.GetHashCode(),
        static value => From(value.Value)
    ) { }

    /// <inheritdoc/>
    public override bool Equals(SampleStringValueObject left, SampleStringValueObject right) => left.Equals(right);

    /// <inheritdoc/>
    public override SampleStringValueObject Snapshot(SampleStringValueObject instance) => From(instance.Value);

    /// <inheritdoc/>
    public override int GetHashCode(SampleStringValueObject instance) => instance.GetHashCode();
}

License

See LICENSE for details.

transparentvalueobjects's People

Contributors

aragas avatar erri120 avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar

Forkers

aragas

transparentvalueobjects's Issues

Augment overhaul

  • Remove TransparentValueObjects.Augments library
  • Add IAugmentWith<T0, T1, ..., TN> interface
  • Add IAugment interface and marker classes
// new
public readonly partial struct MyValueObject : IAugmentWith<
    DefaultValue,
    DefaultEqualityComparer,
    JsonConverter,
    EFCoreSupport> { }

// old
public readonly partial struct SampleValueObjectString :
    IHasDefaultValue<SampleValueObjectString, string>,
    IHasDefaultEqualityComparer<SampleValueObjectString, string>,
    IHasSystemTextJsonConverter,
    IHasEfCore<SampleValueObjectString, string> { }

Pre-defined values support

In cases when the ValueObject has functionality similar to an enum, but a VO would fit better.

I suggest a new Attribute marker ValueObjectInstanceAttribute to mark the values as pre-defined and two new Augments - AllValuesAugment and LimitValuesAugment

  • AllValuesAugment exposes an IEnumerable that returns all pre-defined values
  • LimitValuesAugment limits the From function to only handle the values from pre-definded, throwing if a non pre-defined value is provided.
[ValueObject<int>]
public readonly partial struct SampleIntValueObject : IAugmentWith<DefaultValueAugment, AllValuesAugment>
{
    [ValueObjectInstance]
    public static SampleIntValueObject Default { get; } = From(0);
    [ValueObjectInstance]
    public static SampleIntValueObject Instance1 { get; } = From(1);
    [ValueObjectInstance]
    public static SampleIntValueObject Instance2 { get; } = From(2);
    
    public static SampleIntValueObject DefaultValue => Default;

    // Auto Generated
    public static IEnumerable<SampleIntValueObject> All
    {
        get
        {
            yield return Default;
            yield return Instance1;
            yield return Instance2;
        }
    }
}

[ValueObject<int>]
public readonly partial struct SampleIntValueObject : IAugmentWith<LimitValuesAugment>
{
    [ValueObjectInstance]
    public static SampleIntValueObject Default { get; } = From(0);
    [ValueObjectInstance]
    public static SampleIntValueObject Instance1 { get; } = From(1);
    [ValueObjectInstance]
    public static SampleIntValueObject Instance2 { get; } = From(2);

    // Will throw if values other than 0,1,2 will be suplied to From
}

Generated code is only supported on .NET 7 and newer

Context

TVO generates dead code that is unfriendly towards runtimes that are older than .NET 7.

Explanation

TVO, by default generates types for the following augments, regardless of whether the features are used or not:

  • DefaultEqualityComparerAugment.g.cs
  • DefaultValueAugment.g.cs
  • EfCoreAugment.g.cs
  • JsonAugment.g.cs
  • IDefaultEqualityComparer.g.cs
  • IDefaultValue.g.cs
  • IValueObject.g.cs

The first 4 can only be used on .NET 5 and above due to ExcludeFromCodeCoverage with Justification.

/// <summary>
/// Augment to enable JSON support by generting a JSON converter for the value object.
/// </summary>
/// <remarks>
/// This only supports <c>System.Text.Json</c> at the moment.
/// </remarks>
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage(Justification = "Auto-generated")]
internal sealed class JsonAugment : global::TransparentValueObjects.IAugment { }

The last 3 can only be used on (.NET 6 with LangVersion==preview) or .NET 7+, due to use of static abstract.

/// <summary>
/// Represents the interface for <see cref="global::TransparentValueObjects.DefaultEqualityComparerAugment"/>
/// with members that the consumer has to implement to support the augment.
/// </summary>
internal interface IDefaultEqualityComparer<out TValueObject, TInnerValue>
    where TValueObject : global::TransparentValueObjects.IValueObject<TInnerValue>
    where TInnerValue : notnull
{
    /// <summary>
    /// Gets a equality comparer for the inner value type to be used by default.
    /// </summary>
    public static abstract global::System.Collections.Generic.IEqualityComparer<TInnerValue> InnerValueDefaultEqualityComparer { get; }
}

Expected Outcome

  • Unused code is not generated.

    • This code still ends up in the DLL if not trimmed, increasing size.
  • ExcludeFromCodeCoverage w/ Justification is used on .NET 5+ only. Older runtimes use no justification.

Alternatively source generator warns if TargetFramework is set too low.

Supporting Evidence

When no augments used.

20231205_23h06m37s

Missing XML comment for operators

0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(113,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator ==(CDNName, CDNName)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(114,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator !=(CDNName, CDNName)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(116,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator ==(CDNName, string)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(117,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator !=(CDNName, string)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(119,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator ==(string, CDNName)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(120,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator !=(string, CDNName)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(126,34): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.explicit operator CDNName(string)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(127,34): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.explicit operator string(CDNName)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(142,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator <(CDNName, CDNName)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(143,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator >(CDNName, CDNName)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(144,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator <=(CDNName, CDNName)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(145,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator >=(CDNName, CDNName)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(147,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator <(string, CDNName)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(148,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator >(string, CDNName)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(149,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator <=(string, CDNName)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(150,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator >=(string, CDNName)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(152,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator <(CDNName, string)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(153,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator >(CDNName, string)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(154,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator <=(CDNName, string)'
0>NexusMods.Networking.NexusWebApi.Types.CDNName.g.cs(155,30): Warning CS1591 : Missing XML comment for publicly visible type or member 'CDNName.operator >=(CDNName, string)'

Fix `CS0436`: The type conflicts with the imported type

IValueObject.g.cs(28,50): Warning CS0436 : The type 'IValueObject' in 'TransparentValueObjects/TransparentValueObjects.ValueObjectIncrementalSourceGenerator/IValueObject.g.cs' conflicts with the imported type 'IValueObject' in 'TransparentValueObjects.Sample, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'TransparentValueObjects/TransparentValueObjects.ValueObjectIncrementalSourceGenerator/IValueObject.g.cs'

All code generated as part of the post initialization output is written to the assembly that references the source generator. All of these types are public and inside the TransparentValueObjects namespace.

This means that if project A and project B use the source generator and project B references project A, the compiler will produce warning CS0436 because types like ValueObjectAttribute are within project A and B and have the same namespace.

Nested definitions are not picked up

Works:

[ValueObject<Guid>]
public readonly partial struct MyValueObject { }

Doesn't work:

public class MyClass
{
    [ValueObject<Guid>]
    public readonly partial struct MyValueObject { }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.