Reputation: 39
In my study I have to program a system that get struct of Apartments that contain: apartment code, price, number of rooms and etc.
In other part of the system when the List of apartments are including apartments, I have to build a function that print out to screen all of the apartments that meet all the requirements the user asking for. for example, for this command from user: "PRINT maxRooms 5 Price 20000" the function will scan the List of apartments and print only the apartments that have maximum 5 rooms and their price is less than 20000.
I've initialize those local variables in -1 and now I'm in the stage that if my local variable different from -1 the user asked for this filter. For the sake of simplicity lets assume that we have only three criteria: price, maximum number of rooms, minimum number of rooms.
I'm trying to avoid this situation:
#define UNDEFINED_FILLTER -1
while (currentAprt != NULL)
{
if (maxPrice == UNDEFINED_FILLTER)
{
if (MinimumNumOfRooms == UNDEFINED_FILLTER)
{
if (MaximumNumOfRooms == UNDEFINED_FILLTER)
{
if (1 /*dateofevcation == undefined*/)
{
printf("Apartment code: %d\nApartment address: %s\n Apartment price: %d\n", currentAprt->code,currentAprt->address,currentAprt->price);
printf("Number of rooms: %d\nPossible entry date: %s\nAdding date: %s",currentAprt->numOfRooms,currentAprt->enteryDate,currentAprt->addingDate);
}
else
{
//check date of evacuation criteria
}
}
else
{
//check maximum number of rooms and date of evacuation criteria
}
}
else
{
//check minimum number of rooms, maximum number of rooms and date of evacuation criteria
}
}
else
{
//check max price, minimum number of rooms, maximum number of rooms and date of evacuation criteria
}
currentAprt = currentAprt->next;
}
MY QUESTION: Is there any simple way to check if the user wrote a command with criteria, check it and go for the next criteria? or the only way is to write it with if-else statements?
Upvotes: 0
Views: 87
Reputation: 13196
I find that many complex if-then trees can be greatly simplified by using early returns / early continue:
#define UNDEFINED_FILLTER -1
void loop_over_rooms() {
for (; currentAprt != NULL; currentAprt = currentAprt->next) {
if (maxPrice == UNDEFINED_FILLTER) { continue; }
if (MinimumNumOfRooms == UNDEFINED_FILLTER) { continue; }
if (MaximumNumOfRooms == UNDEFINED_FILLTER) { continue; }
// At this point, we know fields are filled
printf(...);
}
}
Upvotes: 1