-
Notifications
You must be signed in to change notification settings - Fork 162
03. Notifications
There are a few ways to validate your class, let check this out!
The first thing you need to do is inherit from Notifiable class, which is in Flunt.Notifications namespace.
using Flunt.Notifications;
namespace FluntSamples.Entities
{
public class Customer : Notifiable<Notification>
{
}
}
Now you are ready to add notifications to your class.
After inherited from Notifiable class you can use AddNotification or AddNotifications methods, which will add a key/value to your class.
The first parameter is the property or key and the last is your message. Here is a sample:
public Customer(string firstName, string lastName)
{
if (firstName != "Bruce" && lastName != "Wayne")
AddNotification("Name", "You're not Batman!");
}
You can call AddNotification(s) methods everywhere inside your class, since it's inherited from Notifiable.
Now that you have a notification set, you can just use the property Valid ou Invalid to check if you're good to go or not.
var customer = new Customer("André", "Baltieri");
if (customer.Invalid)
{
// Ops, something went wrong
}
You can also check everything that happened just iterating the Notifications property. Check the sample below.
var customer = new Customer("André", "Baltieri");
if (customer.Invalid)
{
foreach (var notification in customer.Notifications)
{
Console.WriteLine($"{notification.Property} - {notification.Message}");
}
}
You can use Notifiable in any class you want, including parent classes, to group notifications.
Let's supose you have more than one class to validade, you can easily use AddNotifications method and just pass the Notifiable classes, as the sample below:
class Program : Notifiable
{
void Main(string[] args)
{
var customer = new Customer("André", "Baltieri");
var order = new Order(customer);
AddNotifications(customer, order);
if (Invalid)
{
foreach (var notification in customer.Notifications)
{
Console.WriteLine($"{notification.Property} - {notification.Message}");
}
}
Console.WriteLine("Hello World!");
}
}
The AddNotifications method accepts any number of Notifiable classes you want. Last we can just call Invalid from our parent/base class and check all the notifications (Customer and Order).
Now that you know what you can do with notifications, check the Design By Contracts to make your code even better!