From 9345562cc88f31792306d92ee7992444b9b1462d Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Wed, 7 Jun 2017 14:57:55 -0700 Subject: docs: Add note about composition to the design guide. --- docs/design_guide.rst | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) (limited to 'docs/design_guide.rst') diff --git a/docs/design_guide.rst b/docs/design_guide.rst index 8ce47041f..6fe54e70e 100644 --- a/docs/design_guide.rst +++ b/docs/design_guide.rst @@ -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 `_ + 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 -------------------------------------------------------------------------------- -- cgit v1.2.3