https://www.vecteezy.com/free-vector/nanny

If-less code. Enumeration classes for strategies.

TodlyCodly
2 min readJan 22, 2022

--

Programming is about making decisions. So there is mighty block :

if (condition)
{
stuff to do if condition is met
}
else
{
other stuff to do if condition is not met
}

No magic here. Magic happens if let say ten developers in row add something.

if (condition)
{
if (condition2)
{
stuff to do if condition2 is met
}
else
{
other stuff to do if condition2 is not met
}
}
else
{
other stuff to do if condition is not met
}

Enumeration class for help

To implement different strategy based on some prior conditions there is other solution. Enumeration class:

Using Enumeration classes instead of enum types | Microsoft Docs

Basic idea is as follows :

public class ClassName
{
public ClassName(args ...){}
public readonly static ClassName StrategyOne = new(args...); public void Handle(){}
}

Class will contain static fields of its type and based on constructor parameters behavior will vary.

Usage is simple:

var handler = ClassName.StrategyOne;

Then in any place of code use:

handler.Handle();

will trigger StrategyOne specific actions.

Some functional help in object oriented world

C# is object oriented and forcing it to be purely functional is bad idea. But functional-like elements could be helpful.

In example project

https://github.com/mes1234/Nanny

There is need for configurable task runner. So configuration is self explanatory without need for detailed documentation:

Runners class has only static function so usage is simple:

await _nannyConfig.StartOptions                             .Runner(functionToRun, _nannyConfig);

Why bother

There might be question why bother to do it. Delegates with Func<Func<Args>> are hard to read. Plain old switch case pattern will do the job.

There are two major pros:

  • As is example library main class doing all the work has only ~40 lines of code. All logic is encapsulated in Options classes.
  • All possible combinations of strategies is supported ‘out of box’. There is no need to code all possible scenarios.

Example project

To ensure that this is really useful not only pure theory. Example github repository is available:

mes1234/Nanny (github.com)

--

--

TodlyCodly

C# developer, who once was Pythonista and dreams of being Golang guy.