Skip to main content Home Creators thebushidocollective han oop-inheritance-composition
oop-inheritance-composition Use when deciding between inheritance and composition in object-oriented design. Use when creating class hierarchies or composing objects from smaller components.
Jump to install Skills Marketplace Discover and explore AI skills built by the community.
Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
Copy promptShow prompt details A direct command skips the review prompt. Inspect the source before running it.
npx skills add https://github.com/TheBushidoCollective/han --skill oop-inheritance-compositionThe command stays on one line. Scroll horizontally to inspect it before copying.
Prefer a local copy? Download the files currently available to SkillsMP.
Download Zip Downloading... More from this repository Related occupations SOC
Based on SOC occupation classification
name oop-inheritance-composition user-invocable false description Use when deciding between inheritance and composition in object-oriented design. Use when creating class hierarchies or composing objects from smaller components. allowed-tools ["Bash","Read"]
OOP Inheritance and Composition
Master inheritance and composition to build flexible, maintainable object-oriented systems. This skill focuses on understanding when to use inheritance versus composition and how to apply each effectively.
Inheritance Fundamentals
Basic Inheritance in Java
public abstract class Vehicle {
private String brand;
private String model;
private int year;
protected double currentSpeed;
protected Vehicle (String brand, String model, int year) {
this .brand = brand;
this .model = model;
this .year = year;
this .currentSpeed = 0.0 ;
}
public final void start () {
performSafetyCheck();
startEngine();
System.out.println(brand + " " + model + " started" );
}
protected void performSafetyCheck () {
System.out.println("Performing basic safety check" );
}
protected abstract void startEngine () ;
public void accelerate (double speed) {
currentSpeed += speed;
System.out.println("Current speed: " + currentSpeed);
}
public void brake (double reduction) {
currentSpeed = Math.max(0 , currentSpeed - reduction);
System.out.println("Current speed: " + currentSpeed);
}
public String getBrand () { return brand; }
public String getModel () { return model; }
public int getYear () { return year; }
public double getCurrentSpeed () { return currentSpeed; }
}
public class Car extends Vehicle {
private int numberOfDoors;
private boolean isSunroofOpen;
public Car (String brand, String model, int year, int numberOfDoors) {
super (brand, model, year);
this .numberOfDoors = numberOfDoors;
this .isSunroofOpen = false ;
}
@Override
protected void startEngine () {
System.out.println("Car engine started with ignition" );
}
@Override
protected void performSafetyCheck () {
super .performSafetyCheck();
System.out.println("Checking doors are closed" );
System.out.println("Checking seatbelts" );
}
public void openSunroof () {
if (currentSpeed == 0 ) {
isSunroofOpen = true ;
System.out.println("Sunroof opened" );
} else {
System.out.println("Stop the car before opening sunroof" );
}
}
public int getNumberOfDoors () {
return numberOfDoors;
}
}
public class Motorcycle extends Vehicle {
private boolean hasWindshield;
public Motorcycle (String brand, String model, int year, boolean hasWindshield) {
super (brand, model, year);
this .hasWindshield = hasWindshield;
}
@Override
protected void startEngine () {
System.out.println("Motorcycle engine started with kick/button" );
}
@Override
public void accelerate (double speed) {
if (currentSpeed + speed > 200 ) {
System.out.println("Warning: Maximum safe speed exceeded!" );
}
super .accelerate(speed);
}
public boolean hasWindshield () {
return hasWindshield;
}
}
Inheritance in Python
from abc import ABC, abstractmethod
from typing import List , Optional
from datetime import datetime
class Employee (ABC ):
"""Abstract base class for all employees."""
def __init__ (self, employee_id: str , name: str , email: str , hire_date: datetime ):
self ._employee_id = employee_id
self ._name = name
self ._email = email
self ._hire_date = hire_date
self ._is_active = True
@property
def employee_id (self ) -> str :
return self ._employee_id
@property
def name (self ) -> str :
return self ._name
@property
def email (self ) -> str :
return self ._email
@property
def hire_date (self ) -> datetime:
._hire_date
( ) -> :
(datetime.now() - ._hire_date).days //
( ) -> :
._is_active:
ValueError( )
base_pay = .calculate_pay()
bonus = .calculate_bonus()
deductions = .calculate_deductions()
total_pay = base_pay + bonus - deductions
.record_payment(total_pay)
total_pay
( ) -> :
( ) -> :
( ) -> :
( ) -> :
( )
( ) -> :
._is_active =
( ):
( ):
().__init__(employee_id, name, email, hire_date)
._annual_salary = annual_salary
( ) -> :
._annual_salary /
( ) -> :
._annual_salary * * .years_of_service
( ):
( ):
().__init__(employee_id, name, email, hire_date)
._hourly_rate = hourly_rate
._hours_worked =
( ) -> :
hours < :
ValueError( )
._hours_worked += hours
( ) -> :
regular_hours = ( ._hours_worked, )
overtime_hours = ( , ._hours_worked - )
regular_pay = regular_hours * ._hourly_rate
overtime_pay = overtime_hours * ._hourly_rate *
regular_pay + overtime_pay
( ) -> :
().record_payment(amount)
._hours_worked =
( ):
( ):
().__init__(employee_id, name, email, hire_date, annual_salary)
._commission_rate = commission_rate
._sales_this_period =
( ) -> :
amount <= :
ValueError( )
._sales_this_period += amount
( ) -> :
base = ().calculate_pay()
commission = ._sales_this_period * ._commission_rate
base + commission
( ) -> :
().record_payment(amount)
._sales_this_period =
Inheritance in TypeScript
abstract class Shape {
protected readonly id : string ;
protected color : string ;
constructor (color : string ) {
this .id = crypto.randomUUID ();
this .color = color;
}
abstract area (): number ;
abstract perimeter (): number ;
abstract draw (): void ;
getColor (): string {
return this .color ;
}
setColor (color : string ): void {
this .color = color;
}
describe (): string {
return `${this .constructor.name} (${this .color} ): Area = ${this .area().toFixed( )} , Perimeter = ` ;
}
}
{
: ;
( ) {
(color);
(radius <= ) {
( );
}
. = radius;
}
(): {
. * . ** ;
}
(): {
* . * . ;
}
(): {
. ( );
}
(): {
. ;
}
}
{
: ;
: ;
( ) {
(color);
(width <= || height <= ) {
( );
}
. = width;
. = height;
}
(): {
. * . ;
}
(): {
* ( . + . );
}
(): {
. ( );
}
(): {
. === . ;
}
}
{
: ;
: ;
: ;
( ) {
(color);
(! . (sideA, sideB, sideC)) {
( );
}
. = sideA;
. = sideB;
. = sideC;
}
( : , : , : ): {
a + b > c && b + c > a && a + c > b;
}
(): {
s = . () / ;
. (s * (s - . ) * (s - . ) * (s - . ));
}
(): {
. + . + . ;
}
(): {
. ( );
}
}
Composition Over Inheritance
Composition in Java
interface Engine {
void start () ;
void stop () ;
int getHorsepower () ;
}
interface Transmission {
void shiftUp () ;
void shiftDown () ;
String getType () ;
}
interface GPS {
void navigate (String destination) ;
String getCurrentLocation () ;
}
class V6Engine implements Engine {
private final int horsepower;
private boolean running;
public V6Engine (int horsepower) {
this .horsepower = horsepower;
this .running = false ;
}
@Override
public void start () {
running = true ;
System.out.println( );
}
{
running = ;
System.out.println( );
}
{
horsepower;
}
}
{
horsepower;
running;
batteryLevel;
{
.horsepower = horsepower;
.batteryLevel = ;
.running = ;
}
{
(batteryLevel > ) {
running = ;
System.out.println( );
} {
System.out.println( );
}
}
{
running = ;
System.out.println( );
}
{
horsepower;
}
{
batteryLevel;
}
}
{
currentGear;
{
.currentGear = ;
}
{
(currentGear < ) {
currentGear++;
System.out.println( + currentGear);
}
}
{
(currentGear > ) {
currentGear--;
System.out.println( + currentGear);
}
}
String {
;
}
}
{
currentGear;
{
.currentGear = ;
}
{
(currentGear < ) {
currentGear++;
System.out.println( + currentGear);
}
}
{
(currentGear > ) {
currentGear--;
System.out.println( + currentGear);
}
}
String {
;
}
}
{
Engine engine;
Transmission transmission;
GPS gps;
String brand;
String model;
{
Engine engine;
Transmission transmission;
GPS gps;
String brand;
String model;
Builder {
.brand = brand;
;
}
Builder {
.model = model;
;
}
Builder {
.engine = engine;
;
}
Builder {
.transmission = transmission;
;
}
Builder {
.gps = gps;
;
}
ComposedCar {
(engine == || transmission == ) {
( );
}
( );
}
}
{
.engine = builder.engine;
.transmission = builder.transmission;
.gps = builder.gps;
.brand = builder.brand;
.model = builder.model;
}
{
engine.start();
System.out.println(brand + + model + );
}
{
engine.stop();
}
{
transmission.shiftUp();
}
{
transmission.shiftDown();
}
{
(gps != ) {
gps.navigate(destination);
} {
System.out.println( );
}
}
String {
String.format( ,
brand, model, engine.getHorsepower(), transmission.getType());
}
}
.Builder()
.brand( )
.model( )
.engine( ( ))
.transmission( ())
.build();
.Builder()
.brand( )
.model( )
.engine( ( ))
.transmission( ())
.build();
Composition in Python
from typing import Protocol, List , Optional
from dataclasses import dataclass
class Renderer (Protocol ):
"""Protocol for rendering components."""
def render (self, content: str ) -> str : ...
class Logger (Protocol ):
"""Protocol for logging components."""
def log (self, message: str , level: str ) -> None : ...
class Validator (Protocol ):
"""Protocol for validation components."""
def validate (self, data: dict ) -> bool : ...
def get_errors (self ) -> List [str ]: ...
class HTMLRenderer :
"""Renders content as HTML."""
def render (self, content: str ) -> str :
return
:
( ) -> :
:
( ):
.filename = filename
( ) -> :
( .filename, ) f:
f.write( )
:
( ) -> :
( )
:
( ):
.errors: [ ] = []
( ) -> :
.errors = []
email = data.get( , )
email:
.errors.append( )
email:
.errors.append( )
email.split( )[ ]:
.errors.append( )
( ) -> [ ]:
.errors
:
( ):
._renderer = renderer
._logger = logger
._validator = validator
( ) -> [ ]:
._logger.log( , )
._validator.validate(user_data):
errors = ._validator.get_errors()
._logger.log( , )
user_content =
rendered = ._renderer.render(user_content)
._logger.log( , )
rendered
:
( ):
._loggers = loggers
( ) -> :
logger ._loggers:
logger.log(message, level)
( ) -> :
._loggers.append(logger)
html_service = UserService(
renderer=HTMLRenderer(),
logger=ConsoleLogger(),
validator=EmailValidator()
)
markdown_service = UserService(
renderer=MarkdownRenderer(),
logger=CompositeLogger([ConsoleLogger(), FileLogger( )]),
validator=EmailValidator()
)
Strategy Pattern with Composition in C
public interface IPaymentStrategy
{
PaymentResult ProcessPayment (decimal amount ) ;
bool IsAvailable () ;
}
public interface IShippingStrategy
{
decimal CalculateCost (decimal weight, string destination ) ;
int EstimateDeliveryDays () ;
}
public interface IDiscountStrategy
{
decimal ApplyDiscount (decimal originalPrice ) ;
}
public class CreditCardPayment : IPaymentStrategy
{
private readonly string _cardNumber;
private readonly string _cvv;
public CreditCardPayment (string cardNumber, string cvv )
{
_cardNumber = cardNumber;
_cvv = cvv;
}
public PaymentResult ProcessPayment (decimal amount )
{
Console.WriteLine( );
PaymentResult.Success(Guid.NewGuid().ToString());
}
=> ;
}
:
{
_email;
{
_email = email;
}
{
Console.WriteLine( );
PaymentResult.Success(Guid.NewGuid().ToString());
}
=> ;
}
:
{
{
weight * m;
}
=> ;
}
:
{
{
weight * m;
}
=> ;
}
:
{
_percentage;
{
_percentage = percentage;
}
{
originalPrice * ( - _percentage / );
}
}
:
{
_amount;
{
_amount = amount;
}
{
Math.Max( , originalPrice - _amount);
}
}
{
IPaymentStrategy _paymentStrategy;
IShippingStrategy _shippingStrategy;
IDiscountStrategy? _discountStrategy;
{
_paymentStrategy = paymentStrategy ?? ArgumentNullException( (paymentStrategy));
_shippingStrategy = shippingStrategy ?? ArgumentNullException( (shippingStrategy));
_discountStrategy = discountStrategy;
}
{
_paymentStrategy = strategy ?? ArgumentNullException( (strategy));
}
{
_shippingStrategy = strategy ?? ArgumentNullException( (strategy));
}
{
_discountStrategy = strategy;
}
{
subtotal = order.Items.Sum(item => item.Price * item.Quantity);
total = _discountStrategy?.ApplyDiscount(subtotal) ?? subtotal;
shippingCost = _shippingStrategy.CalculateCost(order.TotalWeight, order.Destination);
total += shippingCost;
(!_paymentStrategy.IsAvailable())
{
OrderResult.Failed( );
}
paymentResult = _paymentStrategy.ProcessPayment(total);
(!paymentResult.IsSuccess)
{
OrderResult.Failed( );
}
OrderResult.Success(
order.Id,
total,
_shippingStrategy.EstimateDeliveryDays()
);
}
}
processor = OrderProcessor(
CreditCardPayment( , ),
StandardShipping(),
PercentageDiscount( )
);
processor.SetShippingStrategy( ExpressShipping());
processor.SetDiscountStrategy( FixedAmountDiscount( ));
Mixin Pattern
Mixins in Python
from typing import Any
import json
class JsonSerializableMixin :
"""Mixin to add JSON serialization."""
def to_json (self ) -> str :
"""Serialize object to JSON."""
return json.dumps(self .__dict__)
@classmethod
def from_json (cls, json_str: str ) -> Any :
"""Deserialize from JSON."""
data = json.loads(json_str)
return cls(**data)
class TimestampMixin :
"""Mixin to add timestamp tracking."""
def __init__ (self, *args, **kwargs ):
super ().__init__(*args, **kwargs)
self .created_at = datetime.now()
self .updated_at = datetime.now()
def touch (self ) -> None :
"""Update the updated_at timestamp."""
self .updated_at = datetime.now()
class ValidationMixin :
"""Mixin to add validation capabilities."""
def validate (self ) -> bool :
"""Validate object state."""
errors = .get_validation_errors()
(errors) ==
( ) -> [ ]:
errors = []
attr_name, attr_value .__dict__.items():
attr_value attr_name.startswith( ):
errors.append( )
errors
:
( ):
().__init__(*args, **kwargs)
._changes: [ ] = []
( ) -> :
._changes.append({
: field,
: old_value,
: new_value,
: datetime.now()
})
( ) -> [ ]:
._changes.copy()
(TimestampMixin, JsonSerializableMixin, ValidationMixin, AuditMixin):
( ):
().__init__()
._username = username
._email = email
._age = age
( ) -> :
._username
( ) -> :
old_value = ._username
._username = value
.touch()
.record_change( , old_value, value)
( ) -> :
._email
( ) -> :
old_value = ._email
._email = value
.touch()
.record_change( , old_value, value)
( ) -> [ ]:
errors = ().get_validation_errors()
( ._username) < :
errors.append( )
._email:
errors.append( )
._age < :
errors.append( )
errors
user = User( , , )
user.username =
(user.to_json())
(user.get_audit_trail())
(user.validate())
Interface Segregation
Multiple Interfaces in Java
interface Readable {
String read () ;
}
interface Writable {
void write (String content) ;
}
interface Appendable {
void append (String content) ;
}
interface Searchable {
List<String> search (String query) ;
}
class ReadOnlyDocument implements Readable {
private final String content;
public ReadOnlyDocument (String content) {
this .content = content;
}
@Override
public String read () {
return content;
}
}
class Document implements Readable , Writable, Appendable, Searchable {
private StringBuilder content;
public Document (String initialContent) {
this .content = new StringBuilder (initialContent);
}
@Override
String {
content.toString();
}
{
content = (newContent);
}
{
content.append(additionalContent);
}
List<String> {
List<String> results = <>();
String[] lines = content.toString().split( );
(String line : lines) {
(line.contains(query)) {
results.add(line);
}
}
results;
}
}
{
Readable document;
{
.document = document;
}
{
System.out.println(document.read());
}
}
{
Readable readable;
Searchable searchable;
{
.readable = readable;
.searchable = searchable;
}
{
List<String> results = searchable.search(query);
results.forEach(System.out::println);
}
}
When to Use This Skill
Apply inheritance and composition when:
Designing class hierarchies with shared behavior
Modeling IS-A relationships (inheritance)
Modeling HAS-A relationships (composition)
Creating extensible frameworks
Implementing template methods
Building flexible, configurable systems
Avoiding code duplication across related classes
Supporting runtime behavior changes (composition)
Implementing the strategy pattern
Creating plugin architectures
Building testable code with dependency injection
Avoiding deep inheritance hierarchies
Supporting multiple implementations of behavior
Creating reusable components
Implementing interface segregation
Best Practices
Favor composition over inheritance for flexibility
Use inheritance for true IS-A relationships
Keep inheritance hierarchies shallow (2-3 levels max)
Make base classes abstract when appropriate
Use interfaces/protocols for behavior contracts
Prefer small, focused interfaces over large ones
Use dependency injection for composable designs
Document the template method pattern clearly
Override methods properly with super calls when needed
Use final/sealed to prevent further inheritance
Compose behavior from small, single-purpose components
Use the strategy pattern for runtime behavior changes
Avoid protected fields, use protected methods instead
Make composed objects immutable when possible
Test each component independently
Common Pitfalls
Creating deep inheritance hierarchies
Using inheritance for code reuse alone
Inheriting from concrete classes
Breaking Liskov Substitution Principle
Creating God classes with too many responsibilities
Overusing inheritance when composition would work better
Making everything inherit from a common base class
Using protected fields instead of private
Forgetting to call super() in constructors
Creating circular dependencies in composition
Not considering the fragile base class problem
Using implementation inheritance over interface inheritance
Creating tight coupling through inheritance
Not properly overriding equals/hashCode in subclasses
Mixing concerns in base classes
Resources
return
self
@property
def
years_of_service
self
int
return
self
365
def
process_payroll
self
float
"""Process payroll - template method."""
if
not
self
raise
"Cannot process payroll for inactive employee"
self
self
self
self
return
@abstractmethod
def
calculate_pay
self
float
"""Calculate base pay."""
pass
def
calculate_bonus
self
float
"""Calculate bonus - can be overridden."""
return
0.0
def
calculate_deductions
self
float
"""Calculate deductions - can be overridden."""
return
0.0
def
record_payment
self, amount: float
None
"""Record payment."""
print
f"Recording payment of ${amount:.2 f} for {self._name} "
def
deactivate
self
None
"""Deactivate employee."""
self
False
class
SalariedEmployee
Employee
"""Employee paid a fixed salary."""
def
__init__
self,
employee_id: str ,
name: str ,
email: str ,
hire_date: datetime,
annual_salary: float
super
self
def
calculate_pay
self
float
"""Calculate monthly salary."""
return
self
12
def
calculate_bonus
self
float
"""Annual bonus based on years of service."""
return
self
0.01
self
class
HourlyEmployee
Employee
"""Employee paid by the hour."""
def
__init__
self,
employee_id: str ,
name: str ,
email: str ,
hire_date: datetime,
hourly_rate: float
super
self
self
0.0
def
log_hours
self, hours: float
None
"""Log hours worked this period."""
if
0
raise
"Hours cannot be negative"
self
def
calculate_pay
self
float
"""Calculate pay based on hours worked."""
min
self
40
max
0
self
40
self
self
1.5
return
def
record_payment
self, amount: float
None
"""Record payment and reset hours."""
super
self
0.0
class
CommissionEmployee
SalariedEmployee
"""Employee with base salary plus commission."""
def
__init__
self,
employee_id: str ,
name: str ,
email: str ,
hire_date: datetime,
annual_salary: float ,
commission_rate: float
super
self
self
0.0
def
record_sale
self, amount: float
None
"""Record a sale for commission calculation."""
if
0
raise
"Sale amount must be positive"
self
def
calculate_pay
self
float
"""Calculate base salary plus commission."""
super
self
self
return
def
record_payment
self, amount: float
None
"""Record payment and reset sales."""
super
self
0.0
2
${this .perimeter().toFixed(2 )}
class
Circle
extends
Shape
private
radius
number
constructor
color : string , radius : number
super
if
0
throw
new
Error
"Radius must be positive"
this
radius
area
number
return
Math
PI
this
radius
2
perimeter
number
return
2
Math
PI
this
radius
draw
void
console
log
`Drawing a ${this .color} circle with radius ${this .radius} `
getRadius
number
return
this
radius
class
Rectangle
extends
Shape
private
width
number
private
height
number
constructor
color : string , width : number , height : number
super
if
0
0
throw
new
Error
"Dimensions must be positive"
this
width
this
height
area
number
return
this
width
this
height
perimeter
number
return
2
this
width
this
height
draw
void
console
log
`Drawing a ${this .color} rectangle ${this .width} x${this .height} `
isSquare
boolean
return
this
width
this
height
class
Triangle
extends
Shape
private
sideA
number
private
sideB
number
private
sideC
number
constructor
color : string , sideA : number , sideB : number , sideC : number
super
if
this
isValidTriangle
throw
new
Error
"Invalid triangle dimensions"
this
sideA
this
sideB
this
sideC
private
isValidTriangle
a
number
b
number
c
number
boolean
return
area
number
const
this
perimeter
2
return
Math
sqrt
this
sideA
this
sideB
this
sideC
perimeter
number
return
this
sideA
this
sideB
this
sideC
draw
void
console
log
`Drawing a ${this .color} triangle`
"V6 engine started"
@Override
public
void
stop
()
false
"V6 engine stopped"
@Override
public
int
getHorsepower
()
return
class
ElectricEngine
implements
Engine
private
final
int
private
boolean
private
int
public
ElectricEngine
(int horsepower)
this
this
100
this
false
@Override
public
void
start
()
if
0
true
"Electric engine started silently"
else
"Battery depleted!"
@Override
public
void
stop
()
false
"Electric engine stopped"
@Override
public
int
getHorsepower
()
return
public
int
getBatteryLevel
()
return
class
AutomaticTransmission
implements
Transmission
private
int
public
AutomaticTransmission
()
this
1
@Override
public
void
shiftUp
()
if
8
"Automatically shifted to gear "
@Override
public
void
shiftDown
()
if
1
"Automatically shifted to gear "
@Override
public
getType
()
return
"Automatic"
class
ManualTransmission
implements
Transmission
private
int
public
ManualTransmission
()
this
1
@Override
public
void
shiftUp
()
if
6
"Manually shifted to gear "
@Override
public
void
shiftDown
()
if
1
"Manually shifted to gear "
@Override
public
getType
()
return
"Manual"
public
class
ComposedCar
private
final
private
final
private
final
private
final
private
final
public
static
class
Builder
private
private
private
private
private
public
brand
(String brand)
this
return
this
public
model
(String model)
this
return
this
public
engine
(Engine engine)
this
return
this
public
transmission
(Transmission transmission)
this
return
this
public
gps
(GPS gps)
this
return
this
public
build
()
if
null
null
throw
new
IllegalStateException
"Engine and transmission required"
return
new
ComposedCar
this
private
ComposedCar
(Builder builder)
this
this
this
this
this
public
void
start
()
" "
" is ready to drive"
public
void
stop
()
public
void
shiftUp
()
public
void
shiftDown
()
public
void
navigateTo
(String destination)
if
null
else
"GPS not available"
public
getSpecs
()
return
"%s %s - %d HP %s transmission"
ComposedCar
sportsCar
=
new
ComposedCar
"Porsche"
"911"
new
V6Engine
450
new
ManualTransmission
ComposedCar
electricCar
=
new
ComposedCar
"Tesla"
"Model 3"
new
ElectricEngine
283
new
AutomaticTransmission
f"<html><body>{content} </body></html>"
class
MarkdownRenderer
"""Renders content as Markdown."""
def
render
self, content: str
str
return
f"# {content} \n\nRendered as Markdown"
class
FileLogger
"""Logs messages to a file."""
def
__init__
self, filename: str
self
def
log
self, message: str , level: str
None
with
open
self
'a'
as
f"[{level} ] {message} \n"
class
ConsoleLogger
"""Logs messages to console."""
def
log
self, message: str , level: str
None
print
f"[{level} ] {message} "
class
EmailValidator
"""Validates email addresses."""
def
__init__
self
self
List
str
def
validate
self, data: dict
bool
self
'email'
''
if
not
self
"Email is required"
return
False
if
'@'
not
in
self
"Email must contain @"
return
False
if
'.'
not
in
'@'
1
self
"Email must have valid domain"
return
False
return
True
def
get_errors
self
List
str
return
self
class
UserService
"""Service composed of various components."""
def
__init__
self,
renderer: Renderer,
logger: Logger,
validator: Validator
self
self
self
def
create_user
self, user_data: dict
Optional
str
"""Create user using composed components."""
self
f"Creating user: {user_data.get('email' )} "
"INFO"
if
not
self
self
self
f"Validation failed: {errors} "
"ERROR"
return
None
f"User created: {user_data['email' ]} "
self
self
"User created successfully"
"INFO"
return
class
CompositeLogger
"""Logger that delegates to multiple loggers."""
def
__init__
self, loggers: List [Logger]
self
def
log
self, message: str , level: str
None
for
in
self
def
add_logger
self, logger: Logger
None
self
'app.log'
$"Processing ${amount} via credit card"
return
public bool IsAvailable ()
true
public
class
PayPalPayment
IPaymentStrategy
private
readonly
string
public PayPalPayment (string email )
public PaymentResult ProcessPayment (decimal amount )
$"Processing ${amount} via PayPal"
return
public bool IsAvailable ()
true
public
class
StandardShipping
IShippingStrategy
public decimal CalculateCost (decimal weight, string destination )
return
2.5
public int EstimateDeliveryDays ()
7
public
class
ExpressShipping
IShippingStrategy
public decimal CalculateCost (decimal weight, string destination )
return
5.0
public int EstimateDeliveryDays ()
2
public
class
PercentageDiscount
IDiscountStrategy
private
readonly
decimal
public PercentageDiscount (decimal percentage )
public decimal ApplyDiscount (decimal originalPrice )
return
1
100
public
class
FixedAmountDiscount
IDiscountStrategy
private
readonly
decimal
public FixedAmountDiscount (decimal amount )
public decimal ApplyDiscount (decimal originalPrice )
return
0
public
class
OrderProcessor
private
private
private
public OrderProcessor (
IPaymentStrategy paymentStrategy,
IShippingStrategy shippingStrategy,
IDiscountStrategy? discountStrategy = null )
throw
new
nameof
throw
new
nameof
public void SetPaymentStrategy (IPaymentStrategy strategy )
throw
new
nameof
public void SetShippingStrategy (IShippingStrategy strategy )
throw
new
nameof
public void SetDiscountStrategy (IDiscountStrategy? strategy )
public OrderResult ProcessOrder (Order order )
decimal
decimal
decimal
if
return
"Payment method not available"
var
if
return
"Payment failed"
return
var
new
new
"1234-5678-9012-3456"
"123"
new
new
10
new
new
20
self
return
len
0
def
get_validation_errors
self
List
str
"""Get list of validation errors."""
for
in
self
if
is
None
and
not
'_'
f"{attr_name} is required"
return
class
AuditMixin
"""Mixin to add audit trail."""
def
__init__
self, *args, **kwargs
super
self
List
dict
def
record_change
self, field: str , old_value: Any , new_value: Any
None
"""Record a change to the audit trail."""
self
'field'
'old_value'
'new_value'
'timestamp'
def
get_audit_trail
self
List
dict
"""Get the audit trail."""
return
self
class
User
"""User class with multiple mixed-in behaviors."""
def
__init__
self, username: str , email: str , age: int
super
self
self
self
@property
def
username
self
str
return
self
@username.setter
def
username
self, value: str
None
self
self
self
self
'username'
@property
def
email
self
str
return
self
@email.setter
def
email
self, value: str
None
self
self
self
self
'email'
def
get_validation_errors
self
List
str
"""Override to add specific validation."""
super
if
len
self
3
"Username must be at least 3 characters"
if
'@'
not
in
self
"Email must be valid"
if
self
18
"User must be at least 18 years old"
return
"john_doe"
"john@example.com"
25
"jane_doe"
print
print
print
public
read
()
return
@Override
public
void
write
(String newContent)
new
StringBuilder
@Override
public
void
append
(String additionalContent)
@Override
public
search
(String query)
new
ArrayList
"\n"
for
if
return
class
DocumentViewer
private
final
public
DocumentViewer
(Readable document)
this
public
void
display
()
class
DocumentSearcher
private
final
private
final
public
DocumentSearcher
(Readable readable, Searchable searchable)
this
this
public
void
findAndDisplay
(String query)