8000 docs: Add note about composition to the design guide. · sparkfun/circuitpython@9345562 · GitHub
[go: up one dir, main page]

Skip to content

Commit 9345562

Browse files
committed
docs: Add note about composition to the design guide.
1 parent 714521a commit 9345562

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

docs/design_guide.rst

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff 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+
292312
Lots of small modules
293313
--------------------------------------------------------------------------------
294314

0 commit comments

Comments
 (0)
0