Modularity

Splitting a program: one function per task, factoring out repeated code, grouping functions into modules, importing, and separating the main program from what can be reused.

  • 25 cards
  • 5 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. Understand

A few cards from the deck

  • Modularity: what is it?

    Show the answer

    A way of building a program in separate pieces, each with a precise role, which can be written, tested and changed independently of each other.

    A defect is looked for in one piece only, an improvement touches only that piece, and a piece already written is reused in another program.

  • What does python3 main.py print?

    ```python
    # outils.py
    print("loading")

    def double(n):
    return 2 * n

    if __name__ == "__main__":
    print("test", double(4))

    # main.py
    import outils
    print(outils.double(5))
    `

    • loading, then 10
    • 10 alone
    • loading, test 8, then 10
    • test 8, then 10
    Show the answer

    loading, then 10

    Importing runs the file: the file-level print is displayed. But __name__ is then "outils" and not "__main__", so the test block is skipped.

  • Repeated code is replaced by a …: if a defect is fixed, it is fixed … only.

    Show the answer

    Repeated code is replaced by a function: if a defect is fixed, it is fixed once only.

    The three copies of a 10% discount become a single appliquer_remise(prix), and changing the rate is done in one place.

  • Module: what is it?

    Show the answer

    A file that groups together related functions and values, and which another file can use by importing it.

    In Python, any .py file is a module: outils.py is imported under the name outils. Grouping aire and perimetre in geometrie.py says where to look for them.

  • Which of these functions best respects single responsibility?

    • calculer_moyenne(notes)
    • lire_et_afficher_moyenne()
    • traiter_notes_et_ecrire_fichier(notes)
    • programme_complet()
    Show the answer

    calculer_moyenne(notes)

    calculer_moyenne has one task and can be tested without keyboard or file. The other three mix reading, computing, displaying or writing: changing one of these tasks forces you to reopen the others.