Skip to main content

Value Object : You shouldn't have multiple parameterized constructors

Medium
DDD

If you have different behaviours with default values or nullable values : You should have differents Value Object.

If you have different constructors but all constructors call the same constructor, you should use defaults parameters.

Value objects classes are annotated with ValueObject.

Examples

Example 1:

Positive

Correct implementation following the practice.

namespace Practices.DDD.ValueObject.ParametrizedConstructor
{
[ValueObject]
internal class VOSimpleValueConstructor
{
public VOSimpleValueConstructor(int myValue)
{
MyValue = myValue;
}

public int MyValue { get; }
}

[ValueObject]
internal class VOTwoValues
{
public VOTwoValues(int myValue, int secondValue)
{
MyValue = myValue;
SecondValue = secondValue;
}

public int MyValue { get; }
public int SecondValue { get; }
}
}

Negative

Incorrect implementation that violates the practice.

namespace Practices.DDD.ValueObject.ParametrizedConstructor
{
[ValueObject]
internal class VOSimpleValueConstructor
{
public VOSimpleValueConstructor(int myValue)
{
MyValue = myValue;
}

public int MyValue { get; }
}

[ValueObject]
internal class VOTwoValues
{
public VOTwoValues(int myValue, int secondValue)
{
MyValue = myValue;
SecondValue = secondValue;
}

public int MyValue { get; }
public int SecondValue { get; }
}


[ValueObject]
internal class VOMultipleConstructor
{
public VOMultipleConstructor(int myValue)
{
MyValue = myValue;
}

public VOMultipleConstructor(int myValue, int secondValue)
{
MyValue = myValue;
SecondValue = secondValue;
}

public int MyValue { get; }
public int SecondValue { get; }
}

}

Example 2:

Positive

Correct implementation following the practice.

namespace Practices.DDD.ValueObject.ParametrizedConstructor
{
[ValueObject]
internal class VOSimpleValueConstructor
{
public VOSimpleValueConstructor(int myValue)
{
MyValue = myValue;
}

public int MyValue { get; }
}

[ValueObject]
internal class VOTwoValues
{
public VOTwoValues(int myValue, int secondValue)
{
MyValue = myValue;
SecondValue = secondValue;
}

public int MyValue { get; }
public int SecondValue { get; }
}
}