Get to No as fast as possible
- by Tim Hibbard
There is a sales technique where the strategy is to get the customer to say “No deal” as soon as possible. The idea being that by establishing terms that your customer is not comfortable with with, the sooner you can figure out what they will be willing to agree to. The same principal can be applied to code design. Instead of nested if…then statements, a code block should quickly eliminate the cases it is not equipped to handle and just focus on what it is meant to handle. This is code that will quickly become maintainable as requirements change: private void SaveClient(Client c)
{
if (c != null)
{
if (c.BirthDate != DateTime.MinValue)
{
foreach (Sale s in c.Sales)
{
if (s.IsProcessed)
{
SaveSaleToDatabase(s);
}
}
SaveClientToDatabase(c);
}
}
}
If an additional requirement comes along that requires the Client to have Manager approval or for a Sale to be under $20K, this code will get messy and unreadable.
A better way to meet the same requirements would be:
private void SaveClient(Client c)
{
if (c == null)
{
return;
}
if (c.BirthDate == DateTime.MinValue)
{
return;
}
foreach (Sale s in c.Save)
{
if (!s.IsProcessed)
{
continue;
}
SaveSaleToDatabase(s);
}
SaveClientToDatabase(c);
}
This technique moves on quickly when it finds something it doesn’t like. This makes it much easier to add a Manager approval constraint. We would just insert the new requirement before the action takes place.