CSHARPPROGLIB Telegram 6295
💡 Domain Validation в .NET и DDD — просто о сложном

В .NET-проектах часто пишут валидацию прямо в контроллере или сервисе:
— проверили, что поле не пустое,
— число больше нуля,
— email подходит по формату.

Это правильно, но есть проблема — бизнес-правила остаются размазаны по коду.
В итоге можно случайно создать объект в некорректном состоянии (например, заказ без товаров).

В идеале должно быть два уровня валидации Application Validation И Domain Validation. В одном проверяются входные данные, а в другом строится защита сущностей от нарушения бизнес-правил.

Пример проверки на уровне приложения:
public record CreateOrderDto(string CustomerEmail, List<OrderItemDto> Items);

public class OrderApplicationValidator
{
public static void Validate(CreateOrderDto dto)
{
if (string.IsNullOrWhiteSpace(dto.CustomerEmail))
throw new ArgumentException("Email is required");

if (!dto.CustomerEmail.Contains("@"))
throw new ArgumentException("Email format is invalid");

if (dto.Items == null || dto.Items.Count == 0)
throw new ArgumentException("Order must contain at least one item");
}
}


Здесь мы проверяем только корректность ввода.

А вот внутри домена мы защищаем бизнес-правила:
public class OrderItem
{
public string ProductName { get; }
public int Quantity { get; }
public Money Price { get; }

private OrderItem(string productName, int quantity, Money price)
{
ProductName = productName;
Quantity = quantity;
Price = price;
}

public static OrderItem Create(string productName, int quantity, Money price)
{
if (string.IsNullOrWhiteSpace(productName))
throw new InvalidOperationException("Product name cannot be empty");

if (quantity <= 0)
throw new InvalidOperationException("Quantity must be greater than zero");

return new OrderItem(productName, quantity, price);
}

public Money GetTotal() => Money.Create(Quantity * Price.Amount);
}


Когда правила закреплены в домене, они становятся частью самой логики, а не зависимыми от внешних слоёв. Это гарантирует, что объект в принципе невозможно построить в некорректном виде.

🐸Библиотека шарписта

#il_люминатор
Please open Telegram to view this post
VIEW IN TELEGRAM
🔥81👍1



tgoop.com/csharpproglib/6295
Create:
Last Update:

💡 Domain Validation в .NET и DDD — просто о сложном

В .NET-проектах часто пишут валидацию прямо в контроллере или сервисе:
— проверили, что поле не пустое,
— число больше нуля,
— email подходит по формату.

Это правильно, но есть проблема — бизнес-правила остаются размазаны по коду.
В итоге можно случайно создать объект в некорректном состоянии (например, заказ без товаров).

В идеале должно быть два уровня валидации Application Validation И Domain Validation. В одном проверяются входные данные, а в другом строится защита сущностей от нарушения бизнес-правил.

Пример проверки на уровне приложения:

public record CreateOrderDto(string CustomerEmail, List<OrderItemDto> Items);

public class OrderApplicationValidator
{
public static void Validate(CreateOrderDto dto)
{
if (string.IsNullOrWhiteSpace(dto.CustomerEmail))
throw new ArgumentException("Email is required");

if (!dto.CustomerEmail.Contains("@"))
throw new ArgumentException("Email format is invalid");

if (dto.Items == null || dto.Items.Count == 0)
throw new ArgumentException("Order must contain at least one item");
}
}


Здесь мы проверяем только корректность ввода.

А вот внутри домена мы защищаем бизнес-правила:
public class OrderItem
{
public string ProductName { get; }
public int Quantity { get; }
public Money Price { get; }

private OrderItem(string productName, int quantity, Money price)
{
ProductName = productName;
Quantity = quantity;
Price = price;
}

public static OrderItem Create(string productName, int quantity, Money price)
{
if (string.IsNullOrWhiteSpace(productName))
throw new InvalidOperationException("Product name cannot be empty");

if (quantity <= 0)
throw new InvalidOperationException("Quantity must be greater than zero");

return new OrderItem(productName, quantity, price);
}

public Money GetTotal() => Money.Create(Quantity * Price.Amount);
}


Когда правила закреплены в домене, они становятся частью самой логики, а не зависимыми от внешних слоёв. Это гарантирует, что объект в принципе невозможно построить в некорректном виде.

🐸Библиотека шарписта

#il_люминатор

BY Библиотека шарписта | C#, F#, .NET, ASP.NET


Share with your friend now:
tgoop.com/csharpproglib/6295

View MORE
Open in Telegram


Telegram News

Date: |

A Hong Kong protester with a petrol bomb. File photo: Dylan Hollingsworth/HKFP. The public channel had more than 109,000 subscribers, Judge Hui said. Ng had the power to remove or amend the messages in the channel, but he “allowed them to exist.” Judge Hui described Ng as inciting others to “commit a massacre” with three posts teaching people to make “toxic chlorine gas bombs,” target police stations, police quarters and the city’s metro stations. This offence was “rather serious,” the court said. The creator of the channel becomes its administrator by default. If you need help managing your channel, you can add more administrators from your subscriber base. You can provide each admin with limited or full rights to manage the channel. For example, you can allow an administrator to publish and edit content while withholding the right to add new subscribers. Over 33,000 people sent out over 1,000 doxxing messages in the group. Although the administrators tried to delete all of the messages, the posting speed was far too much for them to keep up.
from us


Telegram Библиотека шарписта | C#, F#, .NET, ASP.NET
FROM American