Skip to content

Instantly share code, notes, and snippets.

@Porges
Last active January 17, 2017 04:05
Show Gist options
  • Save Porges/0a079f80ec0b90c4aff9b23ddc3b89c8 to your computer and use it in GitHub Desktop.
Save Porges/0a079f80ec0b90c4aff9b23ddc3b89c8 to your computer and use it in GitHub Desktop.
Examples for the "Ignore Null Strategies" post: https://porg.es/ignore-null-strategies/
interface IProducer
{
Result Produce();
}
class ProducerExample
{
readonly IProducer _producer;
// constructor elided...
public Result Act()
{
if (_producer == null)
{
return Result.Default;
}
return _producer.Produce();
}
}
interface IHandler
{
void Handle();
}
class HandlerExample
{
readonly IHandler _handler;
// constructor elided...
public void Run()
{
if (_handler == null)
{
// some other implementation
}
else
{
_handler.Handle();
}
}
}
class DefaultProducer : IProducer
{
public Result Produce() => Result.Default;
}
class ProducerExampleRevised
{
[NotNull] readonly IProducer _strategy;
// constructor elided...
public Result Run()
{
return _strategy.Produce();
}
}
class ConstantProducer : IProducer
{
public Result Value { get; }
public ConstantProducer(Result value)
{
Value = value;
}
public Result Produce() => Value;
}
class NullHandler : IHandler
{
public void Handle() { }
}
class HandlerExampleRevised
{
[NotNull] readonly IHandler _handler;
// constructor elided...
public void Run()
{
_handler.Handle();
}
}
delegate Result Producer();
static class Producers
{
// Default is a Producer
public static Result Default() => Result.Default;
// Constant returns a Producer, given an argument
public static Producer Constant(Result r) => () => r;
}
class FunctionalProducerExample
{
[NotNull] readonly Producer _strategy;
// constructor elided...
public Result Run()
{
return _strategy();
}
}
delegate void Handler();
static class Handlers
{
// Null is a Handler
public static void Null()
{
}
}
class FunctionalHandlerExample
{
[NotNull] readonly Handler _handler;
// constructor elided...
public void Run()
{
_handler();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment