Okay, this is a very common and good refactoring task! The goal is to fetch the data once per request and then pass it around or make it easily accessible.
Here are a few approaches, ranging from simple to slightly more involved, along with their pros and cons. I'll assume your DB calls are asynchronous (e.g., using motor for MongoDB or asyncpg for PostgreSQL) as is typical in Tornado.
Assumed Structure (Simplified):
# --- db_models.py (example) ---
class Project:
@staticmethod
async def first(criteria=None): # Made it async
# Simulating an async DB call
print("DB CALL: Project.first()")
# In a real app, this would query a database
# e.g., return await db.projects.find_one(criteria or {})
return {"id": 1, "name": "Legacy Project", "config_details": "some_db_config"}
# --- utils.py (example) ---
async def build_task_configuration(project_data):
if not project_data:
# This is the duplicate call we want to remove
print("build_task_configuration fetching project...")
project_data = await Project.first() # Duplicate
if not project_data:
return {"error": "Project not found for task config"}
return {"task_specific_setting": f"derived from {project_data.get('name')}"}
async def build_project_config(project_data):
if not project_data:
# This is another place where it might be fetched, or it might be passed
print("build_project_config fetching project (if not passed)...")
project_data = await Project.first() # Potentially duplicate
if not project_data:
return {"error": "Project not found for project config"}
task_config = await build_task_configuration(project_data) # Pass it down
return {
"project_name": project_data.get("name"),
"base_config": "some_base_config",
"tasks": task_config,
"full_project_data_for_config": project_data # Just for example
}
# --- handlers.py (example) ---
import tornado.web
# from db_models import Project # Assuming Project is accessible
# from utils import build_project_config # Assuming utils are accessible
class ProjectHandler(tornado.web.RequestHandler):
async def get(self, project_id): # Assuming you get an ID, or it's implicit
# 1. First call
print("ProjectHandler.get() fetching project...")
project_data = await Project.first({"id": project_id}) # Assuming first() can take criteria
if not project_data:
self.set_status(404)
self.write({"error": "Project not found"})
return
# 2. This function call leads to another Project.first()
# if project_data is not passed properly down the chain
config = await build_project_config(None) # Simulating the bad call path
# In reality, it might be build_project_config() without args
# or build_project_config(some_other_arg)
self.write({
"project_details_direct": project_data,
"project_configuration": config
})
# Example of running (very basic)
# async def main():
# app = tornado.web.Application([
# (r"/project/(.*)", ProjectHandler),
# ])
# app.listen(8888)
# print("Application is running on port 8888")
# await tornado.ioloop.IOLoop.current().start()
# if __name__ == '__main__':
# tornado.ioloop.IOLoop.current().run_sync(main)
Let's refactor this.
Approach 1: Pass the Fetched Object Down (Dependency Injection)
This is often the cleanest and most explicit way. Fetch the object once in the handler and pass it as an argument to the functions that need it.
Refactored Code:
# --- db_models.py (example - same as before) ---
class Project:
@staticmethod
async def first(criteria=None):
print("DB CALL: Project.first()")
return {"id": 1, "name": "Legacy Project", "config_details": "some_db_config"}
# --- utils_refactored.py ---
async def build_task_configuration_v1(project_data_from_caller): # Renamed arg for clarity
if not project_data_from_caller:
# This function now EXPECTS project_data
raise ValueError("project_data must be provided to build_task_configuration_v1")
# Or handle gracefully: return {"error": "Project data missing"}
print(f"build_task_configuration_v1 using project: {project_data_from_caller.get('name')}")
return {"task_specific_setting": f"derived from {project_data_from_caller.get('name')}"}
async def build_project_config_v1(project_data_from_caller): # Renamed arg
if not project_data_from_caller:
# This function now EXPECTS project_data
raise ValueError("project_data must be provided to build_project_config_v1")
print(f"build_project_config_v1 using project: {project_data_from_caller.get('name')}")
# Pass the fetched project_data down
task_config = await build_task_configuration_v1(project_data_from_caller)
return {
"project_name": project_data_from_caller.get("name"),
"base_config": "some_base_config",
"tasks": task_config
}
# --- handlers_refactored.py ---
import tornado.web
# from db_models import Project
# from utils_refactored import build_project_config_v1
class ProjectHandlerV1(tornado.web.RequestHandler):
async def get(self, project_id=None): # Made project_id optional for simplicity here
# Fetch ONCE
print("ProjectHandlerV1.get() fetching project...")
# Assuming Project.first() can take criteria, or you have Project.get_by_id()
# For this example, let's assume Project.first() gives us the one we need.
project = await Project.first() # Or await Project.get_by_id(project_id)
if not project:
self.set_status(404)
self.write({"error": "Project not found"})
return
# Pass the fetched project to functions that need it
config = await build_project_config_v1(project)
self.write({
"project_details_direct": project,
"project_configuration": config
})
# --- Main to run example (if you want to test it)
# async def main():
# app = tornado.web.Application([
# (r"/project/?.?", ProjectHandlerV1), # Simplified route for example
# ])
# app.listen(8888)
# print("Application is running on port 8888 (V1)")
# await tornado.ioloop.IOLoop.current().start()
# if __name__ == '__main__':
# tornado.ioloop.IOLoop.current().run_sync(main)
- Pros:
- Explicit: Very clear where the data comes from.
- Testable: Helper functions are easier to test in isolation because their dependencies (the
project object) are passed in.
- No Side Effects: Functions don't secretly fetch data.
- Readability: Data flow is easy to follow.
- Cons:
- Parameter Drilling: If you have many nested calls, you might end up passing the
project object through several functions that don't directly use it, just to get it to a deeper function. This can make function signatures longer.
Approach 2: Lazy-Loaded Property on the Handler
You can fetch the project data on demand within the handler and store it as an instance variable (property). Helper functions can then access it from the handler instance.
Refactored Code:
# --- db_models.py (example - same as before) ---
class Project:
@staticmethod
async def first(criteria=None):
print("DB CALL: Project.first()")
return {"id": 1, "name": "Legacy Project", "config_details": "some_db_config"}
# --- utils_refactored.py ---
# For this approach, helper functions need access to the handler or its property.
# Option A: Helper functions are methods of the handler (if they are very specific to it)
# Option B: Helper functions take the handler instance.
# Let's go with Option B for utils, or make them methods for Option A
async def build_task_configuration_v2(handler_instance): # Takes handler
project_data = await handler_instance.get_project() # Access via lazy loader
if not project_data:
return {"error": "Project not found for task config"}
print(f"build_task_configuration_v2 using project: {project_data.get('name')}")
return {"task_specific_setting": f"derived from {project_data.get('name')}"}
async def build_project_config_v2(handler_instance): # Takes handler
project_data = await handler_instance.get_project() # Access via lazy loader
if not project_data:
return {"error": "Project not found for project config"}
print(f"build_project_config_v2 using project: {project_data.get('name')}")
task_config = await build_task_configuration_v2(handler_instance)
return {
"project_name": project_data.get("name"),
"base_config": "some_base_config",
"tasks": task_config
}
# --- handlers_refactored.py ---
import tornado.web
# from db_models import Project
# from utils_refactored import build_project_config_v2, build_task_configuration_v2
class ProjectHandlerV2(tornado.web.RequestHandler):
def __init__(self, application, request, **kwargs):
super().__init__(application, request, **kwargs)
self._project = None # Initialize cache attribute
async def _fetch_project(self):
# In a real scenario, you might use project_id from the path
# project_id = self.path_kwargs.get('project_id')
# return await Project.first({"id": project_id})
return await Project.first()
async def get_project(self):
if self._project is None:
print("ProjectHandlerV2._project is None, fetching...")
self._project = await self._fetch_project()
return self._project
async def get(self, project_id=None):
# Access project via the lazy loader
project = await self.get_project()
if not project:
self.set_status(404)
self.write({"error": "Project not found"})
return
# Helper functions now use self (the handler instance) to get the project
config = await build_project_config_v2(self)
self.write({
"project_details_direct": project, # project is already fetched
"project_configuration": config
})
# --- Main to run example (if you want to test it)
# async def main():
# app = tornado.web.Application([
# (r"/project/?.?", ProjectHandlerV2), # Simplified route for example
# ])
# app.listen(8889)
# print("Application is running on port 8889 (V2)")
# await tornado.ioloop.IOLoop.current().start()
# if __name__ == '__main__':
# tornado.ioloop.IOLoop.current().run_sync(main)
- Pros:
- Reduces Parameter Drilling: Helper functions don't need
project in their signature if they take the handler instance.
- On-Demand Fetching: The DB call happens only when
get_project() is first called.
- Encapsulation: The logic for fetching and caching the project is contained within the handler.
- Cons:
- Coupling: Helper functions become coupled to the
ProjectHandler (or at least expect an object with a get_project() method). This makes them less reusable outside the context of this handler.
- Slightly Less Explicit: You need to know that
handler.get_project() is the way to get the project data, rather than seeing it passed directly.
- Stateful Handler: The handler now has state (
_project). This is fine as Tornado handlers are new per request, but it's something to be aware of.
Approach 3: Context Object (More Advanced, Potentially Overkill for this specific case)
For very complex scenarios with many shared resources in a request, you might introduce a request-scoped context object. However, for just one project object, the handler instance itself (self) in Approach 2 already serves as a kind of request context. This approach is more relevant if you have multiple such objects or complex state to manage across many helper functions.
General Tips for Refactoring:
- Identify the "Source of Truth": In your
ProjectHandler.get(), the first Project.first() call is the one you want to keep. This is where the object should originate for that request.
- Single Responsibility Principle (SRP):
ProjectHandler.get(): Orchestrates the request, fetches primary data, calls helpers, forms response.
build_project_config(): Takes project data, builds a specific config structure.
build_task_configuration(): Takes project data, builds task-specific config.
- Make Changes Incrementally:
- Start by modifying
build_task_configuration to require project_data. Update its caller (build_project_config).
- Then modify
build_project_config to require project_data. Update its caller (ProjectHandler.get()).
- Finally, ensure
ProjectHandler.get() fetches once and passes it down.
- Write Tests (if possible): If you have tests, they can give you confidence that your refactoring hasn't broken anything. If not, consider adding some, especially for the helper functions.
- For Approach 1, testing
build_project_config(mock_project_data) is straightforward.
- For Approach 2, you might need to mock the handler instance or make helper functions methods of a testable class.
- Error Handling: Ensure you handle cases where
Project.first() might return None (or raise an exception) gracefully at the top level (usually in the handler). The helper functions can then assume they receive valid data or raise an error if not.
- Async/Await: Since it's Tornado, ensure all DB calls and functions that call them are
async and properly awaited.
- Readability and Team Conventions: Choose the approach that makes the code most readable and maintainable for your team. Approach 1 is often favored for its explicitness.
Recommendation for Your Case:
Given your description, Approach 1 (Pass the Object Down) is likely the best starting point. It's the most straightforward, explicit, and improves testability significantly. If "parameter drilling" becomes a major issue across many, many functions, then Approach 2 could be considered, perhaps by making the helper functions methods of the ProjectHandler if they are truly specific to it.
Start by refactoring build_task_configuration to accept project_data, then build_project_config, and finally update ProjectHandler.get(). This bottom-up modification of the callees first makes the process smoother.