Vogen icon indicating copy to clipboard operation
Vogen copied to clipboard

Allow NewTonSoft to Serialize Uninitialized Value

Open ziongh opened this issue 6 months ago • 1 comments

Sometimes we need to serialize an object that may not have it's value initialized yet. (ex.: Auditing into Json all changes to an entity before saving to the Database; Auditing the API request the user sent of a Create that may have a non initialized value; etc.)

I've made something simple using only Newtonsoft, but I can expand, if the ideia is approved.

ziongh avatar Jun 05 '25 17:06 ziongh

Hi, Thanks for the PR! I have a couple of thoughts, one is about not needing this functionality and one is about an alternative way to implement this functionality:

Representing uninitialized values

It looks like that in your domain, you have the concept of yet-to-be-initialized values and you are using null to represent this. You could instead use a known instance and use a value that it otherwise unrepresentable, for example:

[ValueObject<int>]
public partial class CustomerId
{
    public static CustomerId Invalid = new(-1);
    public static CustomerId Unspecified = new(-2);
}

Now, you can use CustomerId.Unspecified to represent your yet-to-be-initialized values and these can be happily serialized/deserialized. Plus it's clearer to reader and avoids the ambiguity associated with using nulls.

Continuing with null if the above suggestion isn't workable

I was half way through writing this bit; describing how we could do it, but then changed my mind as it seems wrong. I'll elaborate...

In Vogen, we have the DeserializationStrictness which handles nullness. In the case of deserialization, we have no control over what comes in as the value objects might not have even been serialized as value objects. So we have to be lenient and accept nulls and other values that could fail validation.

But during serialization: this is stuff from our domain. And in our domain, we never want to deal with nulls or uninitialised values (unless, as described above), those uninitialized values are explicit, e.g. CustomerId.Unspecified. My concern is, by allowing nulls to exist in the domain, we might be condoning the usage of nulls and implicitly uninitialized values, which is something that we should be avoiding at all costs in this library. As I say, there's one small area where we are less strict with this, and that's deserialization, where, hopefully, developers handle invalid values in the anti-corruption-layer after deserializing.

What do you think? I really appreciate your effort of doing the PR, and hopefully you can understand why I'm wary of adding such functionality. If the above isn't feasible, then I'm happy to think of other ways to customise Vogen to suit needs that we don't necessarily want to everyone to use.

SteveDunn avatar Jun 06 '25 06:06 SteveDunn