Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an elegant way to make every method in a class start with a certain block of code in C#?

Tags:

c#

I have a class where every method starts the same way:

internal class Foo {
  public void Bar() {
    if (!FooIsEnabled) return;
    //...
  }
  public void Baz() {
    if (!FooIsEnabled) return;
    //...
  }
  public void Bat() {
    if (!FooIsEnabled) return;
    //...
  }
}

Is there a nice way to require (and hopefully not write each time) the FooIsEnabled part for every public method in the class?

I check Is there an elegant way to make every method in a class start with a certain block of code?, but that question is for Java, and its answer are using Java Library.

like image 709
0x6773 Avatar asked Jul 01 '15 05:07

0x6773


People also ask

How many methods a class should have?

a) Methods should not have more than an average of 30 code lines (not counting line spaces and comments). b) A class should contain an average of less than 30 methods, resulting in up to 900 lines of code.

What are methods in classes?

A method is a procedure associated with a class and defines the behavior of the objects that are created from the class.


2 Answers

The principal your are looking for is Interception from the domain of Aspect Oriented Programming or AOP.

While C# does not directly support it, there are solid choices:

  1. Postsharp
  2. Unity Interception
  3. Spring.NET
  4. Castle Interceptors

If I get time tomorrow, I will cook up an example for you...

like image 189
Aaron Anodide Avatar answered Sep 27 '22 20:09

Aaron Anodide


I don't think you can easily get rid of the extra clutter in the Bar, Baz, Bat methods, but you can make it more manageable with creating a method to execute action you are passing in as such.

internal class Foo
{
    private bool FooIsEnabled;

    public void Bar()
    {
        Execute(() => Debug.WriteLine("Bar"));
    }

    public void Baz()
    {
        Execute(() => Debug.WriteLine("Baz"));
    }

    public void Bat()
    {
        Execute(() => Debug.WriteLine("Bat"));
    }

    public void Execute(Action operation)
    {
        if (operation == null)
            throw new ArgumentNullException("operation");

        if (!FooIsEnabled)
            return;

        operation.Invoke();
    }
}
like image 30
Janne Matikainen Avatar answered Sep 27 '22 18:09

Janne Matikainen