Skip to content

Instantly share code, notes, and snippets.

@carloswm85
Created May 16, 2023 11:51
Show Gist options
  • Save carloswm85/4682a8140bacc0ba2bb54dc2669fc225 to your computer and use it in GitHub Desktop.
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.
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