Reputation: 73
I have a some amount of methods. In every method code is repeated. For example something like this
class Sample1
{
public void SampleMethod1()
{
try
{
//Code of Method
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void SampleMethod2()
{
try
{
//Code of Method
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
public void SampleMethod3()
{
try
{
//Code of Method
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Can I do something to not repeat myself? Recently I read something about AOP. Perhaps, it is solution of my question?
Upvotes: 1
Views: 1512
Reputation: 236248
You can create method which accepts Action and tries to execute it:
class Sample1
{
public void SampleMethod1()
{
TryExecute(() => /* code for method */);
}
public void SampleMethod2()
{
TryExecute(() => /* code for method */);
}
private void TryExecute(Action action)
{
try
{
action();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
BTW your sample methods satisfy signature of Action delegate, so you can have method which tries to execute action, and pass 'unsafe' methods to it. I.e. define following method in class which uses Sample1
class:
private void TryExecute(Action action)
{
try
{
action();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Sample methods should not have try-catch logic:
public void SampleMethod1()
{
// code for method
}
public void SampleMethod2()
{
// code for method
}
And usage:
var obj = new Sample1();
TryExecute(obj.SampleMethod1);
TryExecute(obj.SampleMethod2);
Upvotes: 6