I have an automation script used to control other applications(like Browser or DesktopApp).
I’ve created a function with a “while” to determine the current page or state of the application, deciding the next action to execute.
void OuterMostFunc()
{
while(!exit)
{
//InitSomethings...
InnerFunc();
//HandleSomethings...
}
}
void InnerFunc()
{
if(A_Page_Cond)
A_Func();
else if(B_Page_Cond)
B_Func();
...
}
However, at the same time, these applications may be manually operated or encounter unexpected events.
Therefore, I must regularly check for changes in status at many key points and break out to return to the outermost function to reassess the situation.
A more elegant solution involves using Try-Catch, along with customizing a BreakException, allowing me to return to the outermost function from anywhere in the code.
void OuterMostFunc()
{
while(!exit)
{
//InitSomethings...
try
{
InnerFunc();
}
catch(BreakExcetion ex)
{}
//HandleSomethings...
}
}
void Any_Deep_Level_Func()
{
//DoSomethings.
if(CheckPageIsChanged())
throw new BreakException();
//DoSomethings.
}
For a long time, this approach has been useful and reliable.
However, in pursuit of optimal performance due to the application context of the program, the performance overhead brought by Try-Catch becomes difficult to ignore.
For instance, Try-Catch requires tens of milliseconds of execution time, bringing about a relatively substantial performance overhead.
If we were to make all functions return bool (or out bool), and then check whether to return or execute the next step after calling each function, we could swiftly return to the outermost function.
However, this would result in a disastrous impact on the readability of the code.