Refactoring restructures existing code to improve organization, readability, and maintainability without changing the behavior users rely on. AI tools can inspect code, identify redundancy or inefficient algorithms, and suggest improvements, but developers remain responsible for reviewing every change. section 1.1.4 section 5.1
A practical AI-assisted refactoring workflow combines explanation, tests, alternatives, and deliberate verification:
- Ask for a plain-language explanation before changing unfamiliar or legacy code. section 2.2
- Generate tests first or alongside the refactoring so existing behavior and overlooked cases become visible. section 2.2
- Request readability and maintainability improvements, then compare trade-offs between competing approaches. section 2.2
- Test edge cases, related functionality, and database state after each change rather than trusting code that merely looks correct. section 6.2.2
Persisting a question set across refreshes
A Flask application initially called get_question_set() without a session identifier, so each page refresh generated new questions. Refactoring changed the method to accept session_id=None; when an identifier exists, it retrieves the stored question set instead. Reloading the page then keeps the same questions. The change preserves the return type, making it easier to test, but successful startup and unchanged output still require further verification. section 6.2.3 section 6.2.2
def get_question_set(self, session_id=None):
if (session_id is None):
all_questions = self.get_all_questions()
if len(all_questions) < 35:
return "There are not enough questions to generate a set."
question_set = set()
while len(question_set) < 35:
question_id = random.choice(list(all_questions))
question_set.add(question_id)
return list(question_set)
else:
# Get a list of questionIDs
self.cursor.execute("""WITH question_set_info AS (
SELECT DISTINCT question_id
FROM question_sets
WHERE session_id = ?
)
SELECT
questions.id,
questions.correct,
questions.question,
questions.a,
questions.b,
questions.c,
questions.d
FROM questions
JOIN question_set_info
ON questions.id = question_set_info.question_id;"""
,(session_id,))
result = self.cursor.fetchall()
if result is None:
return None
else:
return list(result)
Inspect the session-aware get_question_set implementation, which separates random question generation from retrieval of questions associated with an existing session. section 6.2.3





















