I have a method something like this:
public Something MyMethod()
{
Setup();
Do something useful...
TearDown();
return something;
}
The Setup and TearDown methods are in the base class.
The problem I'm having is that I have to write this type of method over and over again with the Setup() and TearDown() method calls.
EDIT: The tricky part of this method is that "Do something useful..." is specific to this method only. This part is different for every method I create.
Also, I can have MyMethod2, MyMethod3, in a single class. In all cases, I would like to run the setup and teardown
Is there an elegant way of doing this without having to write this every single time?
Perhaps I'm delusional, but is a way to add an attribute to the method and intercept the method call, so I can do stuff before and after the call?
We can call a method from another class by just creating an object of that class inside another class. After creating an object, call methods using the object reference variable.
You just need to make it a static method: public class Foo { public static void Bar() { ... } } Then from anywhere: Foo.
You can also use the instance of the class to call the public methods of other classes from another class. For example, the method FindMax belongs to the NumberManipulator class, and you can call it from another class Test.
Yes you can. It is called recursion .
Just implement this method in abstract base class like this:
public Something MyMethod()
{
Setup();
DoSomethingUsefull();
TearDown();
return something;
}
protected abstract DoSomethingUsefull();
Now you need to override only one method in inherited classes - DoSomethingUsefull()
This is Template Method pattern
Use generics, lambdas and delegates like so:
public SomeThing MyMethod()
{
return Execute(() =>
{
return new SomeThing();
});
}
public T Execute<T>(Func<T> func)
{
if (func == null)
throw new ArgumentNullException("func");
try
{
Setup();
return func();
}
finally
{
TearDown();
}
}
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