I'd like to have common try/catch/finally logic in a decorator-like feature that can "wrap" a function or class method. Consider the scenario:
Class MyClass {
void someMethodA() {
doSomeInitialWork();
try {
doSomething();
} catch (err) {
throw err;
} finally {
doSomeCleanUpWork();
}
}
void someMethodB() {
doSomeInitialWork();
try {
doSomethingElse();
} catch (err) {
throw err;
} finally {
doSomeCleanUpWork();
}
}
}
So on and so forth. The unique parts of each method are just the try
body. If I have a bunch of methods, some which require the same logic, is there a "nice" way to avoid redundant code?
Ideally it could be syntax like:
@wrapper
void someMethodA() {
doSomething();
}
@wrapper
void someMethodB() {
doSomethingElse();
}
MyClassInstance.someMethodA(); // call it like this and the wrapper takes care of everything
but I know those are annotations in Dart and not applicable here.
Aucun commentaire:
Enregistrer un commentaire