Refactor code for clarity and deduplication