André Kuljis
André Kuljis

Reputation: 132

What to do when all methods start with the same condition

In a class, all my methods start with the same if

if (locked)
    return;

Is there a design pattern to use in these situations? There has to be a better way than write the same 2 lines in like 8 methods.

Upvotes: 2

Views: 231

Answers (1)

David Oganov
David Oganov

Reputation: 1374

There's one approach that comes to my mind, it is using Functional Programming

One of ideas behind it is reducing code duplications & reusing common structures in functional programming style.

In your case, I have come up with the following extension method:

private static void ExecuteOnFalse(this bool condition, Action actionToInvokeOnFalse)
{
    if (condition) return !condition;
    actionToInvokeOnFalse.Invoke();
    return !condition;
}

Let's say the main code that you want to execute after the check is this:

public void DoSomething()
{
    // Doing something here
}

Then, you can replace your code with the following one:

locked.ExecuteOnFalse(DoSomething);

And the beauty of the functional programming comes with chaining your methods. You can have different modification of the "ExecuteOnFalse" method, one returning bool & accepting Func as the main action. Then you can chain that method and use it this way:

locked.ExecuteOnFalse(DoSomething).ExecuteOnFalse(DoSomethingElse);

I'd recommend reading Functional Programming with C#. It gives good understanding of Functional Programming and brings good examples. In the beginning of the book they replace regular using() {} structure with the functional approach.

Hope this answer gives you some ideas.

Upvotes: 2

Related Questions