When doing defensive programming, I often have some early-return code. In addition, I need to write some log warning that the function returns because of what problem.
void f(A a) {
var b = a.b;
if (b == null) {
Log.warn('f skip running since b==null');
return;
}
var c = some_func(b);
if (c == null) {
Log.warn('f skip running since c==null');
return;
}
another_func(c);
}
I know I can use null-aware operators like ?. but it cannot print warnings when it is null.
I have also tried another approach:
void f(A a) {
var errorMessage = fCore(a);
if (errorMessage!=null) Log.warn(errorMessage);
}
String fCore(A a) {
var b = a.b;
if (b == null) {
return 'f skip running since b==null';
}
var c = some_func(b);
if (c == null) {
return 'f skip running since c==null';
}
another_func(c);
return null
}
But that is also kind of verbose.
Is there a better approach? Thanks!
EDIT
I call it like:
void outer_func() {
one_func();
f(); // even if f skip running, I want two_func still run, etc
two_func();
...
}
Thus, I cannot simply do something like throw LogWarnException('...') and catch at outermost function.