{"meta":{"title":"横断的関心事の処理","intro":"Copilot Chat は、コードが配置されているメソッドまたは関数の主要な懸念事項以外の懸念事項に関連するコードを回避するのに役立ちます。","product":"GitHub Copilot","breadcrumbs":[{"href":"/ja/copilot","title":"GitHub Copilot"},{"href":"/ja/copilot/tutorials","title":"チュートリアル"},{"href":"/ja/copilot/tutorials/copilot-cookbook","title":"GitHub Copilot クックブック"},{"href":"/ja/copilot/tutorials/copilot-cookbook/refactor-code","title":"コードのリファクタリング"},{"href":"/ja/copilot/tutorials/copilot-cookbook/refactor-code/handle-cross-cutting","title":"横断的に処理する"}],"documentType":"article"},"body":"# 横断的関心事の処理\n\nCopilot Chat は、コードが配置されているメソッドまたは関数の主要な懸念事項以外の懸念事項に関連するコードを回避するのに役立ちます。\n\n横断的関心事は、ログ、セキュリティ、データ検証、エラー処理など、システムの複数の部分に影響を与えるプログラムの側面です。 それらは、コードベース全体にちらばっていて、コードの重複やメンテナンスの課題の原因になる可能性があります。\n\nCopilot Chat は、Aspect-Oriented プログラミング (AOP) プラクティスの実装を提案するか、デコレーターとミドルウェア パターンを使用してモジュール式の保守可能な方法でこれらの懸念を一元化することで、横断的な懸念をリファクタリングするのに役立ちます。\n\n## サンプル シナリオ\n\nログが行われる複数のサービス ファイルを含む Python プロジェクトがあるとします。 ログされる情報は、個々のサービス ファイル内で定義されています。 将来、アプリケーションが変更または拡張される場合、この設計のため、ログ エントリの内容とスタイルに不整合が生じる可能性があります。 ログの動作を統合して一元化し、これがプロジェクト全体に広がるのを防ぐことができます。\n\nこのプロジェクト例には、エントリ ポイント ファイル (`main.py`)、ログ メッセージ構成ファイル (`logging_config.py`)、サービス ファイル (`order_service.py`) という 3 つのファイルがあります。 サービス ファイルの例では、ログ情報の定義方法と、アプリケーションの特定の部分のビジネス ロジックが示されています。\n\n### main.py\n\n```python\nimport logging\nfrom logging_config import setup_logging\nfrom payment_service import PaymentService\nfrom order_service import OrderService\nfrom shipping_service import ShippingService\nfrom inventory_service import InventoryService\nfrom notification_service import NotificationService\n\ndef main():\n    setup_logging()\n    payment_service = PaymentService()\n    order_service = OrderService()\n    shipping_service = ShippingService()\n    inventory_service = InventoryService()\n    notification_service = NotificationService()\n\n    # Example usage\n    payment_service.process_payment({\"amount\": 100, \"currency\": \"USD\"})\n    order_service.place_order({\"item\": \"Book\", \"quantity\": 1})\n    shipping_service.ship_order({\"item\": \"Book\", \"quantity\": 1})\n    inventory_service.update_inventory(\"Book\", -1)\n    notification_service.send_notification(\"Order has been placed and shipped.\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\n### logging\\_config.py\n\n```python\nimport logging\n\ndef setup_logging():\n    logging.basicConfig(level=logging.INFO,\n                  format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n```\n\n### order\\_service.py\n\n```python\nimport logging\n\nclass OrderService:\n    def __init__(self):\n        self.logger = logging.getLogger(__name__)\n\n    def place_order(self, order):\n        self.logger.info(\"Entering place_order method.\")\n        try:\n            # In here would be the business logic for placing an order\n            # ...\n            self.logger.info(\"Order placed successfully.\")\n        except Exception as e:\n            self.logger.error(f\"Error in place_order method: {e}\")\n            raise\n        finally:\n            self.logger.info(\"Exiting place_order method.\")\n```\n\n## プロンプトの例\n\nVS CodeまたはVisual Studioでプロジェクト ワークスペースを開き、Copilot Chat ビューに次のプロンプトを入力します。\n\n```copilot copy\n@workspace Refactor this project by using AOP to avoid logging that has cross-cutting concerns\n```\n\n> \\[!NOTE]\n> `@workspace`とVS CodeのVisual Studio チャット参加者は、ワークスペース内のすべてのコードに関するコンテキストをCopilotに提供します。 `@workspace`は、プロジェクトの構造やコードのさまざまな部分の相互作用を考慮したいときにCopilotを使用できます。 JetBrains IDE を使っている場合は、`@project` ではなく `@workspace` を使ってください。\n\n## 応答の例\n\nCopilot は次のように応答します。\n\n> \\[!NOTE] 次の応答は例です。 Copilot Chat の応答は非決定的であるため、ここで示したものとは異なる応答が返される可能性があります。\n\n> アスペクト指向プログラミング (AOP) を使ってこのプロジェクトをリファクタリングし、ログを横断的関心事として処理するには、`aspectlib` などのライブラリを使用できます。 これを行う方法を次に示します。\n>\n> 1.\n\n`aspectlib` をインストールします。\n\n> `pip install aspectlib`\n>\n> 1.\n\n`logging_aspect.py` という名前の新しいファイルでログのアスペクトを作成します。\n\n> ```python\n> import aspectlib\n> import logging\n>\n> @aspectlib.Aspect(bind=True)\n> def log_method_call(cutpoint, *args, **kwargs):\n>     logger = logging.getLogger()\n>     method_name = cutpoint.__name__\n>     logger.info(f\"Entering method: {method_name}\")\n>     try:\n>         result = yield aspectlib.Proceed\n>         logger.info(f\"Method {method_name} executed successfully.\")\n>         return result\n>     except Exception as e:\n>         logger.error(f\"Error in method {method_name}: {e}\")\n>         raise\n>     finally:\n>         logger.info(f\"Exiting method: {method_name}\")\n> ```\n>\n> 1.\n\n`main.py` のサービス メソッドにそのアスペクトを適用します。\n\n> ```python\n> import logging\n> from logging_config import setup_logging\n> from payment_service import PaymentService\n> from order_service import OrderService\n> from shipping_service import ShippingService\n> from inventory_service import InventoryService\n> from notification_service import NotificationService\n> from logging_aspect import log_method_call\n> import aspectlib\n>\n> def main():\n>     setup_logging()\n>\n>     # Apply logging aspect to service methods\n>     aspectlib.weave(PaymentService.process_payment, log_method_call)\n>     aspectlib.weave(OrderService.place_order, log_method_call)\n>     aspectlib.weave(ShippingService.ship_order, log_method_call)\n>     aspectlib.weave(InventoryService.update_inventory, log_method_call)\n>     aspectlib.weave(NotificationService.send_notification, log_method_call)\n>\n>     payment_service = PaymentService()\n>     order_service = OrderService()\n>     shipping_service = ShippingService()\n>     inventory_service = InventoryService()\n>     notification_service = NotificationService()\n>\n>     # Example usage\n>     payment_service.process_payment({\"amount\": 100, \"currency\": \"USD\"})\n>     order_service.place_order({\"item\": \"Book\", \"quantity\": 1})\n>     shipping_service.ship_order({\"item\": \"Book\", \"quantity\": 1})\n>     inventory_service.update_inventory(\"Book\", -1)\n>     notification_service.send_notification(\"Order has been placed and shipped.\")\n>\n> if __name__ == \"__main__\":\n>     main()\n> ```\n\nCopilot 次に、すべてのサービス クラスからログ コードを削除するように指示し、変更されたファイルのコードを提供します。 たとえば、次に示すのは `order_service.py` の改訂版です。\n\n```python\nclass OrderService:\n    def place_order(self, order):\n        # In here would be the business logic for placing an order\n        # ...\n        pass\n```\n\nリファクタリング後のバージョンのプロジェクトでは、同じログ操作が実行されますが、ログのコードは 1 つのファイルに一元化されています。\n\n## 詳細については、次を参照してください。\n\n* [GitHub Copilot Chat のプロンプト エンジニアリング](/ja/copilot/concepts/prompting/prompt-engineering)\n* [GitHub Copilot の使用に関するベスト プラクティス](/ja/copilot/get-started/best-practices)"}