Copilot Chat can help you avoid code that relates to a concern other than the core concern of the method or function in which the code is located.
Cross-cutting concerns are aspects of a program that affect multiple parts of the system, such as logging, security, data validation, and error handling. They can become scattered throughout a codebase, leading to code duplication and maintenance challenges.
Copilot Chat can help refactor cross-cutting concerns by suggesting the implementation of Aspect-Oriented Programming (AOP) practices or using decorators and middleware patterns to centralize these concerns in a modular, maintainable way.
Example scenario
Imagine you have a Python project that contains multiple service files in which logging occurs. The information that gets logged is defined within each of the individual service files. If the application is modified or extended in future, this design could lead to inconsistency in the content and style of log entries. You can consolidate and centralize the logging behavior to avoid this being distributed across your project.
Here are three files from our example project: the entry point file (main.py), the log message configuration file (logging_config.py), and one of the service files (order_service.py). The example service file shows how log information is defined alongside the business logic for a particular part of the application.
import loggingclass OrderService: def __init__(self): self.logger = logging.getLogger(__name__) def place_order(self, order): self.logger.info("Entering place_order method.") try: # In here would be the business logic for placing an order # ... self.logger.info("Order placed successfully.") except Exception as e: self.logger.error(f"Error in place_order method: {e}") raise finally: self.logger.info("Exiting place_order method.")
Example prompt
Open the project workspace in VS Code or Visual Studio and enter the following prompt in the Copilot Chat view.
@workspace Refactor this project by using AOP to avoid logging that has cross-cutting concerns
The @workspace chat participant in VS Code and Visual Studio provides Copilot with context about all of the code in your workspace. You can use @workspace when you want Copilot to consider the structure of your project and how different parts of your code interact. If you're using a JetBrains IDE, use @project rather than @workspace.
Example response
Copilot responds as follows.
The following response is an example. Copilot Chat responses are non-deterministic, so you may get a different response from the one shown here.
To refactor this project using Aspect-Oriented Programming (AOP) to handle logging as a cross-cutting concern, you can use a library like aspectlib. Here is how you can do it:
Install aspectlib:
pip install aspectlib
Create an aspect for logging in a new file called logging_aspect.py:
import aspectlibimport logging@aspectlib.Aspect(bind=True)def log_method_call(cutpoint, *args, **kwargs): logger = logging.getLogger() method_name = cutpoint.__name__ logger.info(f"Entering method: {method_name}") try: result = yield aspectlib.Proceed logger.info(f"Method {method_name} executed successfully.") return result except Exception as e: logger.error(f"Error in method {method_name}: {e}") raise finally: logger.info(f"Exiting method: {method_name}")
Apply the aspect to the service methods in main.py:
Copilot then tells you to remove the logging code from all of the service classes, and gives you the code for the revised files. For example, this is the revised version of order_service.py:
class OrderService: def place_order(self, order): # In here would be the business logic for placing an order # ... pass
In the refactored version of the project, the same logging operations are performed, but the logging code is centralized in a single file.