Created
May 16, 2023 11:51
-
-
Save carloswm85/4682a8140bacc0ba2bb54dc2669fc225 to your computer and use it in GitHub Desktop.
Example of a model class using C# based on domain-driven design principles, including attributes and behaviors.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Product | |
{ | |
// The attributes have private setters, meaning they can only be modified from within the class itself. | |
public int Id { get; private set; } | |
public string Name { get; private set; } | |
public decimal Price { get; private set; } | |
public DateTime CreatedAt { get; private set; } | |
public DateTime? UpdatedAt { get; private set; } | |
public Product(string name, decimal price) | |
{ | |
ValidateName(name); | |
ValidatePrice(price); | |
Id = GenerateUniqueId(); | |
Name = name; | |
Price = price; | |
CreatedAt = DateTime.Now; | |
} | |
public void UpdateName(string newName) | |
{ | |
ValidateName(newName); | |
Name = newName; | |
UpdatedAt = DateTime.Now; | |
} | |
public void UpdatePrice(decimal newPrice) | |
{ | |
ValidatePrice(newPrice); | |
Price = newPrice; | |
UpdatedAt = DateTime.Now; | |
} | |
private void ValidateName(string name) | |
{ | |
if (string.IsNullOrWhiteSpace(name)) | |
{ | |
throw new ArgumentException("Name cannot be empty or whitespace."); | |
} | |
} | |
private void ValidatePrice(decimal price) | |
{ | |
if (price <= 0) | |
{ | |
throw new ArgumentException("Price must be greater than zero."); | |
} | |
} | |
private int GenerateUniqueId() | |
{ | |
// Logic to generate a unique identifier for the product | |
// This can be based on database auto-increment, GUID, or other mechanisms | |
// For simplicity, we'll use a random number for the example | |
return new Random().Next(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment