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

I have a class where each method starts in 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 good way to require (and hopefully not write every time) a FooIsEnabled part for every public method in the class?

I check Is there an elegant way to get every method in a class to start with a specific block of code? , but this question is for Java, and its answer uses the Java library.

+6
source share
3 answers

The principle you are looking for is interception from a domain Aspect-oriented programming or AOP.

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

If I get time tomorrow, I will prepare you an example ...

+7
source

I don’t think that you can easily get rid of unnecessary clutter in the Bar, Baz, Bat methods, but you can make it more manageable by creating a method to perform the action that you pass 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(); } } 
+4
source

Sure:

 internal interface IFoo { void Bar(); void Baz(); void Bat(); } internal class Foo { private IFoo FooImplementation = new DisabledFoo() // or new EnabledFoor() public bool FooIsEnabled { get { return FooImplementation is EnabledFoo; } set { FooImplementation = value ? new EnabledFoo() : new DisabledFoo() } } public void Bar() { FooImplementation.Bar(); } public void Baz() { FooImplementation.Baz(); } public void Bat() { FooImplementation.Bat(); } } internal class EnabledFoo : IFoo { public void Bar() { //... } public void Baz() { //... } public void Bat() { //... } } internal class DisabledFoo : IFoo { public void Bar() {} public void Baz() {} public void Bat() {} } 

And if you intend to mock the foo implementation for unit testing, just let go of the FooIsEnabled property and make FooImplementation public. In this case, you should also get rid of DisabledFoo and test with an instance, for example:

 var fooImplementationMock = new Mock<IFoo>(); var foo = new Foo { FooImplementation = fooImplementationMock.Object }; foo.Bar(); fooImplementationMock.Verify(f => f.Bar()); 

if you use moq .

+2
source

Source: https://habr.com/ru/post/990066/


All Articles