Understanding Business Rules vs. Trivial Validation in .NET C#
Understanding Business Rules vs. Trivial Validation in .NET C#
In the realm of software development, particularly when dealing with business logic and data validation, it’s crucial to distinguish between business rules and trivial validation. This distinction not only affects how we write our code but also the adaptability and scalability of our systems. Let’s delve into this topic with a practical .NET C# example.
Example Overview
Consider a simple online bookstore system. In this scenario, we’ll explore two types of logic: one that represents trivial validation and another that encapsulates a business rule.
public class OnlineBookstoreService
{
private readonly IBookInventory _bookInventory;
public OnlineBookstoreService(IBookInventory bookInventory)
{
_bookInventory = bookInventory;
}
// Method to process book order
public void ProcessBookOrder(int bookId, int quantity)
{
// Trivial Validation
if (bookId <= 0)
{
throw new ArgumentException("Invalid book ID.");
}
// Business Rule
if (!_bookInventory.IsBookAvailable(bookId, quantity))
{
throw new InvalidOperationException("Requested quantity is not available in inventory.");
}
// Proceed with order processing
var orderDetails = new OrderDetails(bookId, quantity);
_bookInventory.UpdateInventory(bookId, -quantity);
// Other order processing logic
}
}
Explanation
Trivial Validation: The check if (bookId <= 0) is a form of trivial validation. It's static, unlikely to change, and checks for basic correctness of input data.
Business Rule: The line if (!_bookInventory.IsBookAvailable(bookId, quantity)) embodies a business rule. It's dynamic and dependent on the current state of the system (i.e., the book inventory). This rule can evolve over time based on business needs.
Redefining Validation with Strong Types
To further refine our system, we can introduce a strong type for bookId to encapsulate the validation logic.
public record BookId
{
public int Value { get; }
public BookId(int value)
{
if (value <= 0)
throw new ArgumentException("Book ID must be positive.");
Value = value;
}
public static implicit operator int(BookId bookId) => bookId.Value;
}
Now, ProcessBookOrder can be modified to accept BookId as a parameter, pushing trivial validation to a higher level in the code and focusing on business rules within the method.
Conclusion
Understanding and appropriately implementing business rules and trivial validation in a system leads to cleaner, more maintainable, and scalable code. By separating these concerns, we can focus on the core business logic and allow our systems to evolve more naturally and flexibly.
Cheers👋
Follow me on LinkedIn: www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&followMember=admir-live