I'm looking for a "right" location to do assertions on values of an object in C#. Most example I've encountered so far do these assertions in the Service of even in the View, but to me it seems more appropriate to do this in the property setter.
As an example I have a Product entity class, where I do the assertions for Null and NullOrWhiteSpace in the setters.
public class Product
{
private string _name;
private ProductCategory _category;
public string Name
{
get => _name;
private set
{
Guard.Against.NullOrWhiteSpace(value, nameof(value));
_name = value;
}
}
public string Allergens { get; set; }
public ProductCategory Category
{
get => _category;
set
{
Guard.Against.Null(value, nameof(value));
_category = value;
}
}
public Product(string name, string allergens, ProductCategory category)
{
Name = name;
Allergens = allergens;
Category = category;
}
}
This would then be used in a service, but as I said, in most examples I see the assertions I do in the domain model setters, are done in the Service.
public class ProductService : IProductService
{
private readonly IAsyncRepository<Product> _productRepository;
private readonly IAsyncRepository<ProductCategory> _productCategoryRepository;
public ProductService(
IAsyncRepository<Product> productRepository,
IAsyncRepository<ProductCategory> productCategoryRepository)
{
_productRepository = productRepository;
_productCategoryRepository = productCategoryRepository;
}
public async Task CreateProductAsync(string name, string allergens, int productCategoryId)
{
var category = await _productCategoryRepository.FindByIdAsync(productCategoryId);
var product = new Product(name, allergens, category);
await _productRepository.AddAsync(product);
}
}
Of course, there could be a lot more assertions, like maximum string length, e-mail address, etc... I know there are C# attributes that I could use, but they are part of frameworks and I want to have as few dependencies as possible in this project.
Could someone explain to me if this would be a good way to do these assertions and why?
Aucun commentaire:
Enregistrer un commentaire