Software Development and Design · Topic 5 of 7
Functions, Classes, Modules and Design Patterns
See why code is organised into functions, classes and modules, and how the MVC and Observer design patterns keep programs flexible and easy to maintain.
- 4 min
- A function does one job and is reused by calling it.
- A class groups data and methods, and an object is an instance of a class.
- A module is a Python file and a package is a folder of modules.
What it is
Well organised code is split into small named pieces, and design patterns are proven ways of arranging those pieces.
Functions, classes and modules are the three building blocks in Python. Patterns such as MVC and Observer describe how larger parts of a program talk to each other.
The benefit is code that is easier to read, test, reuse and change.
How it works
Each level of organisation hides detail and lets you reuse work.
Functions
A function is a named block of code that does one job. It takes input as arguments and can return a result.
def build_vlan_command(vlan_id, name):
return f"vlan {vlan_id}\n name {name}"
print(build_vlan_command(10, "SALES"))
Benefits of functions:
- Reuse. Write the logic once and call it many times.
- Readability. A good name explains what the code does.
- Testing. A small function is easy to test on its own.
- Fewer mistakes. A fix in one place applies everywhere.
Classes
A class groups data and the functions that work on that data. A function inside a class is called a method. An object is one instance of a class.
class Device:
def __init__(self, hostname, ip):
self.hostname = hostname
self.ip = ip
def describe(self):
return f"{self.hostname} at {self.ip}"
r1 = Device("R1", "10.0.0.1")
print(r1.describe())
Classes support encapsulation, which keeps data and behaviour together, and inheritance, in which one class builds on another. A Router class could inherit from Device and add routing features.
Modules and packages
A module is a Python file that holds functions, classes and variables. You use it with import. A package is a folder of modules.
import json
from vlan_tools import build_vlan_command
Modules stop one file growing too large, and they let different projects share the same code. The standard library is a large set of ready made modules.
Design patterns
A design pattern is a general solution to a problem that appears again and again in software. It is a template for structure, not finished code.
Model View Controller (MVC)
MVC splits an application into three parts.
| Part | Role |
|---|---|
| Model | Holds the data and the business rules |
| View | Shows the data to the user |
| Controller | Takes user input and updates the model and the view |
The advantage is separation of concerns. You can change the screen design without touching the data logic, and several views can use one model.
Teams can also work on the parts in parallel. Many web frameworks use this idea.
Observer
In the Observer pattern, one object called the subject keeps a list of observers. When the subject changes state, it notifies every observer automatically.
class Subject:
def __init__(self):
self.observers = []
def subscribe(self, observer):
self.observers.append(observer)
def notify(self, event):
for observer in self.observers:
observer(event)
alerts = Subject()
alerts.subscribe(lambda e: print("log:", e))
alerts.notify("interface down")
The advantage is loose coupling. The subject does not need to know what its observers do, and you can add or remove observers freely.
Observer is the idea behind event driven systems. A webhook is a similar notification model between systems, and a network device that sends an alert to several monitoring tools follows the same idea.
Think of Observer as publish and subscribe. The subject publishes a change and every subscribed observer receives it.
What to remember for the exam
Seven facts cover this topic.
- A function does one job and is reused by calling it.
- A class groups data and methods, and an object is an instance of a class.
- A module is a Python file and a package is a folder of modules.
- Organising code improves reuse, readability, testing and maintenance.
- MVC separates Model, View and Controller.
- Observer lets one subject notify many observers when it changes.
- Both patterns reduce coupling between parts of a program.
Common mistakes
Three mistakes are typical.
Mixing up the roles in MVC. The model holds data and rules, the view shows them, and the controller handles input. Business logic does not belong in the view.
Confusing Observer with a loop that polls. In Observer the subject pushes the change to observers. They do not keep asking.
Thinking a pattern is a library. A pattern is an idea about structure. You write the code yourself.
Do not mix up a class and an object. The class is the blueprint and the object is a thing built from it.
Check yourself
Work through these three questions.
What are the three parts of MVC and what does each do?
The model holds data and rules, the view shows the data, and the controller handles user input and updates the model and view.
In the Observer pattern, what happens when the subject changes?
The subject notifies all of its observers automatically, so they can react.
Why put related functions into a module?
It keeps files small and lets different projects reuse the same code.
Topic 5 of 7 in Software Development and Design
Test yourself on Software Development and Design
The full Cisco CCNA 200-901 DEVASC question bank has 808 questions, with timed practice exams and an explanation for every answer.
This study guide is independent and is not affiliated with, endorsed by, or sponsored by Cisco. Vendor names, certification names and exam codes are trademarks of their respective owners and are used for identification only.