Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad to perform two different tasks in the same loop? [closed]

I'm working on a highly-specialized search engine for my database. When the user submits a search request, the engine splits the search terms into an array and loops through. Inside the loop, each search term is examined against several possible scenarios to determine what it could mean. When a search term matches a scenario, a WHERE condition is added to the SQL query. Some terms can have multiple meanings, and in those cases the engine builds a list of suggestions to help the user to narrow the results.

Aside: In case anyone is interested to know, ambigous terms are refined by prefixing them with a keyword. For example, 1954 could be a year or a serial number. The engine will suggest both of these scenarios to the user and modify the search term to either year:1954 or serial:1954.

Building the SQL query and the refine suggestions in the same loop feels somehow wrong to me, but to separate them would add more overhead because I would have to loop through the same array twice and test all the same scenarios twice. What is the better course of action?

like image 853
Scott Avatar asked Nov 28 '22 06:11

Scott


1 Answers

I'd probably factor out the two actions into their own functions. Then you'd have

foreach (term in terms) {
    doThing1();
    doThing2();
}

which is nice and clean.

like image 70
sprugman Avatar answered Jan 02 '23 20:01

sprugman