Skip to main content

Entity : An Entity unchanged over time could be a Value Object

Medium
DDD

If your entity doesn't change over time, it could be a Value Object.

If a class annotated with Entity has fields that are not readonly but never written or updated (except in constructors), then the practice is not followed and the class should be a Value Object, and fields marked as readonly.

Examples

Example 1:

Positive

Correct implementation following the practice.

namespace CurrencyConverter.Domain
{
[ValueObject]
public class Currency
{
private readonly string _name;

public Currency(string name)
{
_name = name;
}

public override bool Equals(object obj)
{
return obj is Currency currency
&& _name.Equals(currency._name);
}

public override int GetHashCode()
{
return (_name != null ? _name.GetHashCode() : 0);
}

public bool Is(string currencyName)
{
return _name.Equals(currencyName);
}

}
}

Negative

Incorrect implementation that violates the practice.

namespace CurrencyConverter.Domain
{
[Entity]
public class Currency
{
private string _name;

public Currency(string name)
{
_name = name;
}

public string Name => _name;


public bool Is(string currencyName)
{
return Name.Equals(currencyName);
}
}
}