Domain Modeling
- Why? - Learn how Value Objects are used to effectively model domain concepts and represent real-world entities in code. README.md
- How? - Value Objects provide a way to represent strongly typed domain objects that are immutable, providing several benefits. README.md
Value Objects
- Define: A strongly typed (strongly, not stringly) domain object that is immutable. README.md
- Implementation:
- Instead of using primitives such as
int
, Value Objects are used. README.md - Derived from the
ValueObject
type. README.md - Example: README.md
public class CustomerId : ValueObject { }
- Instead of using primitives such as
Value Object Validation
- Why? - Enforces constraints on Value Objects, ensuring they are valid and meet domain requirements. README.md
- Implementation:
public class CustomerId : ValueObject { public override Validation Validate() => Value > 0 ? Validation.Ok : Validation.Invalid("Customer IDs cannot be zero or negative."); }
- Benefits:
Primitive Obsession
- Definition: Using primitive data types to represent domain ideas, which can lead to issues like improper validation, lack of type safety, and difficulty in representing complex domain concepts. README.md
- Code Smell: “Primitive Obsession is using primitive data types to represent domain ideas” README.md
- Example: README.md
int customerId = 42
- Issues:
Benefits of Using Value Objects
- Type Safety: Value Objects enhance type safety, preventing accidental misuse of data. README.md
- Improved Code Readability: Code becomes more readable by using dedicated types for domain concepts. README.md
- Reduced Errors: Value Objects help reduce the risk of errors by enforcing validation and immutability. README.md
- Encapsulation: Value Objects encapsulate data and behavior related to a domain concept. README.md
Examples
- Method Signature: README.md
- Primitive type example:
public void DoSomething(int customerId, int supplierId, int amount)
- Value Object example:
public void DoSomething(CustomerId customerId, SupplierId supplierId, Amount amount)
- Primitive type example:
- Object Creation: README.md
- Primitive type example:
int customerId = 42;
- Value Object example:
var customerId = CustomerId.From(42);
- Primitive type example:
Additional Resources
- For an alternative, more performant approach to Value Objects, please see https://github.com/SteveDunn/Vogen README.md
## 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.