Often I need to get some data and process it in some way. For example getting a list of customers from an API and assemble some summary data on them. As an example, getting :
api_result = api.request('customers/get')
for item in api_result:
customer = Customer.fromDict(item)
process_customer(customer)
This works but the data processing is coupled with the data retrieval. Ideally I'd like to be able to separate the retrieval of the customers from the processing so the code is less coupled. I'd like to instead be able to have something like:
def get_customers()
customers = []
api_result = api.request('customers/get')
for item in api_result:
customer = Customer.fromDict(item)
customers.append(customer)
return customers
...
customers = get_customers()
for customer in customers:
process_customer(customer)
But this forces me to implement the loop twice. One loop is to hydrate the customer object from the API result, and then another loop is to process the data.
Is there a design pattern or way to separate these two steps yet still only loop over the data once? (Or is it just accepted that these will usually be two separate steps with two loops? I am using python, but I'm interested in the general case)