ValueOf icon indicating copy to clipboard operation
ValueOf copied to clipboard

Public parameterless constructor required in order to use generic ValueOf<TValue, TThis>

Open ricardovicentini opened this issue 5 years ago • 3 comments

I think the requirement of a parameterless constructor should be fixed in order to avoid the creation of invalid objects which is an antipattern regarding DDD

ricardovicentini avatar Feb 27 '21 20:02 ricardovicentini

Do you mean there should be a parameterless instance constructor? Currently the only parameterless constructor is a private static. This is run once per type TThis and is required to construct the factory method for creating instances using ValueOf<TThis>.From(TValue).

Paul-Williams avatar Jun 05 '21 14:06 Paul-Williams

I think he means the problem that the library does not prohibit this:

public class Email : ValueOf<string, Email>
{
}

var email = new Email();

So later on, when you start using the type, you will get some NullReference exceptions.

I am not sure if the expectation of everyone playing nice and using the factory method is a good one.

Having a mandatory constructor of T instead would make the wrting of the classes a little bit more ugly, but would get rid of this problem.

Ergamon avatar Jul 19 '21 17:07 Ergamon

I had a very similar library to this one, with the major difference being that validation wasn't optional as it was required in the constructor, e.g.

public class Age : ValueObject<int>
{
    public Age(int value) : base(value, x => x < 0 : "negative age" : string.Empty) { }
}

The base class would call the provided delegate and throw if it returned anything other than an empty string.

The down side is two heap allocations, one for the instance itself, and one for the delegate.

SteveDunn avatar Sep 05 '21 07:09 SteveDunn