Reputation: 4842
I want to be able to perform a text search where the user can choose which flags to set before performing the search. Currently, I have a bunch of if/else statements that performs different searches based on the set flags. Is there a way to simplify this?
Here's what I have so far:
void FindDialog::on_btn_find_clicked()
{
const QString find_term = ui->le_find->text();
bool found;
getConditions();
//direction: true -> go backward, false -> go forward
if(dir)
{
//area: true -> description area, false -> example area
if(area)
found = te_desc_ptr->find(find_term, QTextDocument::FindBackward);
else
found = te_code_ptr->find(find_term, QTextDocument::FindBackward);
} else {
if(area)
found = te_desc_ptr->find(find_term);
else
found = te_code_ptr->find(find_term);
}
this->close();
}
void FindDialog::getConditions()
{
//check conditions
//Area: True = Description, False = Example
//Direction: True = Up, False = Down
area = ui->rbtn_desc->isChecked();
dir = ui->rbtn_up->isChecked();
case_sen = ui->cbx_case->isChecked();
whole = ui->cbx_whole->isChecked();
regx = ui->cbx_reg->isChecked();
}
The code looks if the user selected a checkbox and chooses which kind of search to perform. I'd really like to simplify the code so that there are less find() statements. Obviously, if I add more options, then there will be more if/else statements. How can I go about changing this?
Upvotes: 0
Views: 146
Reputation: 98816
You can collapse the if
tree down to this:
auto textArea = area ? te_desc_ptr : te_code_ptr;
auto findFlags = dir ? QTextDocument::FindBackward : QTextDocument::FindFlags(0);
textArea->find(find_term, findFlags);
I'd also consider renaming area
and dir
, as it's not at all obvious what they signify just from their names.
Upvotes: 3