Be mindful of whether a function mutates a variable or not

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the dumb-mistakes-and-gotchas category.

Last Updated: 2024-03-28

I had the following code to (lazily) build up an SQL query (via an ORM) to search for tutors:

tutors = Tutors.active
tutors.where(skype_available: true) if skype_available
tutors.where(in_person_available: true) if in_person_available
tutors.where(institution: institution) if institution
tutors.where(law_level: law_level) if law_level

return tutors

This returned all active tutors in the database no matter what input I gave (e.g. for skype_available or in_person_available)

My mistake was that I had forgotten to re-assign the expanded queries to the tutors variable. Here's the fix:

tutors = tutors.where(skype_available: true) if skype_available
tutors = tutors.where(in_person_available: true) if in_person_available
tutors = tutors.where(institution: institution) if institution
tutors = tutors.where(law_level: law_level) if law_level

return tutors

Lesson

Be mindful of whether a function mutates a variable's state or leaves it intact (and instead returns a modified version of the data)