File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -289,6 +289,26 @@ SPI Example
289289 i2c.readinto(self .buf)
290290 return self .buf[0 ]
291291
292+ Use composition
293+ --------------------------------------------------------------------------------
294+
295+ When writing a driver, take in objects that provide the functionality you need
296+ rather than taking their arguments and constructing them yourself or subclassing
297+ a parent class with functionality. This technique is known as composition and
298+ leads to code that is more flexible and testable than traditional inheritance.
299+
300+ .. seealso :: `Wikipedia <https://en.wikipedia.org/wiki/Dependency_inversion_principle>`_
301+ has more information on "dependency inversion".
302+
303+ For example, if you are writing a driver for an I2C device, then take in an I2C
304+ object instead of the pins themselves. This allows the calling code to provide
305+ any object with the appropriate methods such as an I2C expansion board.
306+
307+ Another example is to expect a `DigitalInOut ` for a pin to toggle instead of a
308+ `microcontroller.Pin ` from `board `. Taking in the `~microcontroller.Pin ` object
309+ alone would limit the driver to pins on the actual microcontroller instead of pins
310+ provided by another driver such as an IO expander.
311+
292312Lots of small modules
293313--------------------------------------------------------------------------------
294314
You can’t perform that action at this time.
0 commit comments