I have general question regarding composition and function forwarding. Let’s assume we have a struct
car which is composed of a motor and a horn:
struct car
m::Motor
h::Horn
end
Both of it’s components implement a function change!
which allows us to modify internals:
change!(m::Motor; num_pistons=4) = println("change number of pistons") # dummy function
change!(h::Horn; decibel=90) = println("change volume of tooting") # dummy function
Now my natural intention is to try to forward this behaviour to the car itself. For example, the call
change!(x::car, num_pistons=6, decibel=100)
should result in change!(x.motor, num_pistons=6)
and change!(x.horn, decibel=100)
. However, additionally I want to have the following behaviour:
- keyword arguments are optional, so that we can choose to modify only a subset of (car) components
- if two components have the same keyword argument implemented, use it in both
change!
functions - if one keyword argument can not be resolved, give an error
- low runtime costs
Is there an elegant way of achieving this? Is this design itself questionable and should be done differently (maybe by instead implementing change_motor!
and change_horn!
for a car)?