Immutability in StringlyTyped
Motivation:
This package provides a simple implementation of a ValueObject in .NET. This ensures data integrity and prevents accidental modifications.
Why Immutability?
ValueObjects enforce immutability to ensure data integrity and prevent accidental modification. Consider this:
public void DoSomething(int customerId, int supplierId, int amount)
The compiler won’t catch if you accidentally swap customerId
and supplierId
. But by using ValueObjects, this signature becomes much more strongly typed:
public void DoSomething(CustomerId customerId, SupplierId supplierId, Amount amount)
This prevents callers from messing up the ordering of parameters and guarantees that the objects themselves are valid and immutable.
ValueObject Implementation
The package’s ValueObject
type provides the foundation for creating immutable objects. It is a generic class:
public class CustomerId : ValueObject
{
}
The Value
property is private and set only during instantiation. It enforces that the value is not altered directly, ensuring the object’s immutability.
Validation
ValueObjects can include validation logic to ensure data integrity. For example, a CustomerId
should not be zero or negative:
public class CustomerId : ValueObject
{
public override Validation Validate() => Value > 0
? Validation.Ok
: Validation.Invalid("Customer IDs cannot be zero or negative.");
}
Benefits of Immutability
- Stronger Typing: ValueObjects promote strongly typed code, making it easier to understand and maintain.
- Data Integrity: Immutability ensures data consistency and prevents accidental modification.
- Single Point of Validation: Validation rules are enforced at creation, preventing invalid objects from entering the system.
- Thread Safety: Immutable objects are inherently thread-safe, simplifying concurrent programming.
Example Usage:
var customerId = CustomerId.From(42);
The From
method creates a new instance of CustomerId
, validating the provided value.
Additional Resources:
Source:
## Top-Level Directory Explanations
<a class='local-link directory-link' data-ref="samples/" href="#samples/">samples/</a> - This directory contains example projects demonstrating the usage of StringlyTyped library.
<a class='local-link directory-link' data-ref="src/" href="#src/">src/</a> - This directory contains the source code of the StringlyTyped library.
<a class='local-link directory-link' data-ref="tests/" href="#tests/">tests/</a> - This directory contains unit tests for the StringlyTyped library. It includes benchmark tests and small tests.