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.
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.
A method is a procedure associated with a class and defines the behavior of the objects that are created from the class.
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:
If I get time tomorrow, I will cook up an example for you...
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With