Skip to content

Instantly share code, notes, and snippets.

@cameronpresley
Created July 14, 2020 02:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameronpresley/482e10f3edf6dc2f1f4eb71a9c92604d to your computer and use it in GitHub Desktop.
Save cameronpresley/482e10f3edf6dc2f1f4eb71a9c92604d to your computer and use it in GitHub Desktop.
LTE Mars Rover - Designing Logger
public class ItemRepository
{
private readonly string _connectionString;
// By adding the dependency here, there's no way you that
// an ItemRepository could be created without specifying
// a connection string.
public ItemRepository(string connectionString)
{
_connectionString = connectionString;
}
}
// Example usage
// If the connectionString isn't provided, then
// the code doesn't compile!
var itemRepository = new ItemRepository("Data Source=localhost;Initial Catalog=AdventureWorks;Integrated Security=True")
public class PurchaseWorkflow
{
// By adding the NotificationStrategy here,
// there's no way that a developer can call
// the Complete method without specifying
// a way to notify the customer.
public void Complete(Order order, INotificationStrategy strategy)
{
string receiptDetails = CreateReceipt(order);
strategy.SendNotification(order.Customer, receiptDetails);
}
}
// Example Usage
var order = new Order("Cameron", 22.50);
var workflow = new PurchaseWorkflow();
// If a NotificationStrategy isn't passed in, this code won't compile.
workflow.Complete(order, new TextNotificationStrategy());
public class PurchaseWorkflow
{
// By having the notification be set as a property,
// developer can set this dependency once and then
// only change it when needed.
// However, there's nothing forcing a developer to
// set this property.
public INotificationStrategy NotificationStrategy {get; set;}
public void Complete(Order order)
{
string receiptDetails = CreateReceipt(order);
NotificationStrategy.SendNotification(order.Customer, receiptDetails);
}
}
// The Mistake
var order = new Order("Cameron", 22.50);
var workflow = new PurchaseWorkflow();
workflow.Complete(order); // This will cause a NullReferenceException to be thrown
// Proper Usage
var order = new Order("Cameron", 22.50);
var workflow = new PurchaseWorkflow();
// As long as you remember to set this property, things should work!
workflow.NotificationStrategy = new TextNotificationStrategy();
workflow.Complete(order);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment