Core Principles of Composition
メニューを表示するにはスワイプしてください
Composition focuses on building complex objects by combining simpler, independent components. Instead of relying on inheritance, which creates rigid hierarchies, composition allows classes to collaborate through contained objects. This approach makes systems more flexible, modular, and easier to maintain, since components can be replaced or extended without breaking the entire structure.
example.py
Order does not implement payment, inventory, or shipping logic itself.
Instead, it has separate objects (Payment, Inventory, Shipping) and uses them to complete its work.
Each component has one responsibility, and Order only coordinates them.
If you want to change how payment or shipping works, you can replace the component without modifying the Order class.
A few pitfalls to watch for when using composition are creating god objects that collect too many components and become difficult to manage, leaking component APIs through the outer class instead of keeping a clean interface, and introducing hidden coupling when components depend too much on each other's internal details.
A god object tries to do too much. It holds many components and handles many responsibilities, which makes the class hard to understand, test, and maintain.
This happens when the outer class exposes the internal methods or attributes of its components. Instead of providing its own clean interface, it forces users to interact with internal objects directly.
Components become tightly connected through internal details. Changing one part unexpectedly breaks another because they rely on each other's internal structure instead of clear contracts.
フィードバックありがとうございます!
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください