dry - C# Repeated code in methods -
i have amount of methods. in every method code repeated. example 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 not repeat myself? read aop. perhaps, solution of question?
you can create method accepts action , tries execute it:
class sample1 { public void samplemethod1() { tryexecute(() => /* code method */); } public void samplemethod2() { tryexecute(() => /* code method */); } private void tryexecute(action action) { try { action(); } catch (exception ex) { console.writeline(ex.message); } } } btw sample methods satisfy signature of action delegate, can have method tries execute action, , pass 'unsafe' methods it. i.e. define following method in class 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 method } public void samplemethod2() { // code method } and usage:
var obj = new sample1(); tryexecute(obj.samplemethod1); tryexecute(obj.samplemethod2);
Comments
Post a Comment