DEV Community

Luis Rodrigues
Luis Rodrigues

Posted on

.NET: Call Func delegates from Dictionary objects

How about store Func delegates in a Dictionary object and invoke them when you really need them?

This approach can help us to avoid having nested conditional in our code and keep its cyclomatic complexity lower.

“Cyclomatic complexity is a software metric used to determine the complexity of a program”. Click here to know more about that.

For example, suppose we want to create a method that returns a result from a math operation between two numbers. Its result will depend on the operation type that the user will provide to us: addition, subtraction, multiplication, and division.

A simple way to solve that is by creating a method that accepts three parameters: a number that will apply some operation and the operation type. Like this:

As you can see, we need to add four conditions to this method. From that, we have the cyclomatic complexity metric below:

nested conditions

Now check the same method with a Dictionary type that stores Func delegates:

In this case, we don’t need a lot of “if” statements in our code and it’s getting easier to read. Also as you can see in the picture below our cyclomatic complexity is lower than in the first approach:

without nested conditions

Of course, this sample is so simple. Now, try to think how easier can be our life in complex scenarios where we need to support code with higher cyclomatic complexity.

How about buying me a coffee? :D

buy me a coffe?

Discussion (0)