-
Notifications
You must be signed in to change notification settings - Fork 38
Using Notifications
Notifications were created to provide a simple (Simple as possible) key/value explaining something that happened on your code.
Is not a good practice to throw exceptions on your validations, in fact exceptions must be used when you don't know how to manage something, like a database connection which was interrupted for some reason.
Exceptions has a high cost on processors and your code is interrupted immediately, causing you to fallback to user screen. This is a sample we want to avoid:
public class Customer
{
public Customer(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
if(FirstName.Length < 3)
throw new Exception("Invalid First Name");
if (LastName.Length < 3)
throw new Exception("Invalid Last Name");
}
public string FirstName { get; private set; }
public string LastName { get; private set; }
}
If your user sends an invalid first and last name, it will fall on first name, interrupt your code. The user will fix it's first name, and then, boom... last name is wrong...
What about using notifications? Simply inherit from Notifiable class and..
public class Customer : Notifiable
{
public Customer(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
if(FirstName.Length < 3)
AddNotification("FirstName", "FirstName is invalid");
if (LastName.Length < 3)
AddNotification("LastName", "LastName is invalid");
}
public string FirstName { get; private set; }
public string LastName { get; private set; }
}
As soon as your class inherited from Notifiable, you'll also have a new way to validate it:
var customer = new Customer("", "");
if (!customer.IsValid)
Console.WriteLine("Your data is invalid");
foreach (var item in customer.Notifications)
Console.WriteLine(item.Message);