Refactor and optimize code for the book