Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mcintyre321/valueof
Deal with Primitive Obsession - define ValueObjects in a single line (of C#).
https://github.com/mcintyre321/valueof
ddd domain-model valueobject
Last synced: 3 days ago
JSON representation
Deal with Primitive Obsession - define ValueObjects in a single line (of C#).
- Host: GitHub
- URL: https://github.com/mcintyre321/valueof
- Owner: mcintyre321
- License: mit
- Created: 2017-08-08T21:11:25.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2023-03-27T18:23:17.000Z (almost 2 years ago)
- Last Synced: 2025-01-08T00:00:14.659Z (10 days ago)
- Topics: ddd, domain-model, valueobject
- Language: C#
- Homepage:
- Size: 20.5 KB
- Stars: 894
- Watchers: 24
- Forks: 40
- Open Issues: 20
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# ValueOf
> install-package ValueOf
## What is this library
> The Smell: Primitive Obsession is using primitive data types to represent domain ideas. For example, we use a String to represent a message, an Integer to represent an amount of money, or a Struct/Dictionary/Hash to represent a specific object.
> The Fix: Typically, we introduce a ValueObject in place of the primitive data, then watch like magic as code from all over the system shows FeatureEnvySmell and wants to be on the new ValueObject. We move those methods, and everything becomes right with the world.
> - http://wiki.c2.com/?PrimitiveObsessionValueOf lets you define ValueObject Types in a single line of code. Use them everywhere to strengthen your codebase.
```
public class EmailAddress : ValueOf { }...
EmailAddress emailAddress = EmailAddress.From("[email protected]");
```
The ValueOf class implements `.Equals` and `.GetHashCode()` for you.
You can use C# 7 Tuples for more complex Types with multiple values:
```
public class Address : ValueOf<(string firstLine, string secondLine, Postcode postcode), Address> { }```
### Validation
You can add validation to your Types by overriding the `protected void Validate() { } ` method:
```
public class ValidatedClientRef : ValueOf
{
protected override void Validate()
{
if (string.IsNullOrWhiteSpace(Value))
throw new ArgumentException("Value cannot be null or empty");
}
}```
## See Also
If you liked this, you'll probably like another project of mine [OneOf](https://github.com/mcintyre321/OneOf) which provides Discriminated Unions for C#, allowing stronger compile time guarantees when writing branching logic.