GolamMostafa:
What is about this one:
while(Serial.available() && Serial.read());
instead of the following--
byte n = Serial.available();
for (int i=0; i<n; i++)
{
char c = Serial.read(); //read and discard
}
You're still missing the point. The difference between those two statements is so minor that worry about the difference is more trouble than it's worth, and it still has nothing to do with the problem I was addressing. This is a discussion about, as the OP said, "several deeply nested if/else statements".
I'll show you an example. A real example from work. In short, this code is passed a data structure that contains a group of potential operations that we could perform on the device we are connected to. Each operation contains a list of alternate options we can use for the job (like different configuration numbers). Each alternative contains a list of prerequisite values to check on the connected device to determine if that alternative is the correct one. So this one function is checking a group of groups of groups and returns true if at least one of the operations has exactly one alternative that matches all of the prerequisite values, and false otherwise. If that last sentence made your head spin, congratulations, you're a normal human being. Just recently I had to modify this function to add a 4th layer to the bottom of the grouping (So that each prerequisite value could have a list of possible values instead of only one), and I ripped this whole nonsense out, replacing it with 4 separate functions that each dealt with only one layer of the structure, and it's about 8,000 times nicer to look at.
I've stripped out all the contents (since it's company property), but I've left the skeleton of control structures in place so that you can get an idea of the madness. It's 50 lines in its barebones form here, but with all the other code in it it was almost 3 times longer. Just imagine yourself debugging this, trying to trace a path through this labyrinth, and keeping track of which values affected by which previous values of all the iterations would send you down which paths. I can tell you that it made me cross-eyed.
bool ValidatePrerequisites( )
{
for(unsigned long i = 0; ; i++)
{
for(unsigned long j=0; ; j++)
{
for(unsigned long d=0; ; d++)
{
if( )
{
continue;
}
if( )
{
}
if( )
{
if ( ) {
for(short e = 0; ; e++){
if( ){
}
}
if( ){
break;
}
}
else if( )
{
break;
}
}
}
if( )
{
}
if( )
{
}
}
if( )
{
if( )
{
}
else {
}
return false;
}
}
return true;
}
This is bad. This is too be avoided, because it's very hard for human short-term memory to deal with this entire structure all at once. This monstrosity is 7 levels at its deepest and 130 lines long. When I refactored it into separate functions, they max out at 2 levels deep and are between 15 - 40 lines long. 4 small functions are much easier to deal with than one big mass of spaghetti.