What am I suppose to do
I am working on an API, where I get a list of objects from the output of an SQL query using an ORM. Now this API call needs to send following information down to the client.
Output consists of a list and a dictionary. List contains dictionaries holding statistical data per day. One dictionary for each day.
Dictionary contains aggregate of all the statistical data in the same time period along with a status indicating how much did the value go down or up depending upon aggregate of previous N days prior to current N days requested.
Current Implementation
So, I got a requested of data for last N days. I fetched last 2N days of data from the database. Looped over the result and while I prepared data according to the API if the data was for the last N days. While the loop was in, I kept creating aggregated data for previous N days and current N days for calculating the change.
Once the loop got over, I created the dictionary having current aggregate and the change per stat.
What's the issue?
The function is just too big. I can separate out the the process into two functions but then I will have to loop over the data again. How do I ensure that the code looks sane and refactored without affecting the performance.
1 Answer 1
When you have a big loop that also mutates state, the way to refactor it is to create a method object . It's an object from a new class whose fields correspond to all the messy local state that you're now maintaining while iterating through the loop.