docs: Add note about composition to the design guide.
This commit is contained in:
parent
714521a4c7
commit
9345562cc8
@ -289,6 +289,26 @@ SPI Example
|
||||
i2c.readinto(self.buf)
|
||||
return self.buf[0]
|
||||
|
||||
Use composition
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
When writing a driver, take in objects that provide the functionality you need
|
||||
rather than taking their arguments and constructing them yourself or subclassing
|
||||
a parent class with functionality. This technique is known as composition and
|
||||
leads to code that is more flexible and testable than traditional inheritance.
|
||||
|
||||
.. seealso:: `Wikipedia <https://en.wikipedia.org/wiki/Dependency_inversion_principle>`_
|
||||
has more information on "dependency inversion".
|
||||
|
||||
For example, if you are writing a driver for an I2C device, then take in an I2C
|
||||
object instead of the pins themselves. This allows the calling code to provide
|
||||
any object with the appropriate methods such as an I2C expansion board.
|
||||
|
||||
Another example is to expect a `DigitalInOut` for a pin to toggle instead of a
|
||||
`microcontroller.Pin` from `board`. Taking in the `~microcontroller.Pin` object
|
||||
alone would limit the driver to pins on the actual microcontroller instead of pins
|
||||
provided by another driver such as an IO expander.
|
||||
|
||||
Lots of small modules
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user