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.
- Concepts
- Questions
- Sort and link
- Scenarios
- 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.pyprint?
```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, then1010aloneloading,test 8, then10test 8, then10
Show the answer
loading, then10Importing runs the file: the file-level
printis 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
.pyfile is a module:outils.pyis imported under the nameoutils. Groupingaireandperimetreingeometrie.pysays 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_moyennehas 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.