Modular Design
Modular Design
Modular Programming
Modular programming is a technique that simplifies complex software
development by breaking it down into smaller, manageable pieces called
modules. Each module performs a specific task and can be used independently
or combined with other modules to build larger systems. This approach offers
several benefits such as easier code maintenance, update simplicity, and the
reusability of code across projects.
Modular programming organizes code into distinct sections with specific
functions.
Key principles include high cohesion within modules and loose coupling
between them.
Advantages include easier updates, reusability of code, and efficient
teamwork.
Challenges might involve increased code volume and complexity for
smaller projects.
Definition of Module
A module in Python is a file that contains Python code, such as functions,
variables, classes, or methods, that can be imported into another Python
program:
Modules are similar to code libraries and help to organize Python code
logically. They can be used to group related code into a single file, making it
easier to understand and use.
Components of a Module
A module is like a little box that contains three main things:
Interface - This is the part of the module that talks to the outside world.
It's like a list of commands that other parts of the program can use.
Implementation - This is the secret sauce inside the module. It's all the
code and steps that make the module work but aren't shown to everyone.
Data structures - These are like the module's personal notebooks. They
hold all the information the module needs to do its tasks. Keeping this
info inside the module helps keep things neat and tidy.
Types of Modules
Modules can be different kinds:
Program control modules - These are the bosses. They manage how the
program starts, ends, deals with mistakes, interacts with users, and makes
sure other modules are working together nicely.
Specific task modules - These are the specialists. They focus on doing
one thing really well, like working with numbers, managing text, or
talking to devices.
For example, in Python programming:
import platform - that provides system information.
import math - Deals with mathematical functions.
import datetime - display the current date
Modular Design Patterns
Here are some design patterns that help with modular programming:
Facade - Makes a simple front for more complex interactions between
modules.
Adapter - Lets modules that normally wouldn't work together connect
through a middleman.
Bridge - Keeps the big ideas separate from the nitty-gritty details, so you
can change them independently.
Using these patterns can help keep the connections between modules clean and
easy to manage.
Advantages of Modular Programming
Easier to keep up - Since each part does its own thing, updating, fixing, or
adding new stuff doesn't mess with the rest. Different developers can
work on their own parts at the same time.
Use parts again - You can take a module you've made and use it in
another project. This saves time because you don't have to start from
scratch every time.
Simpler to handle - Splitting a big program into smaller parts makes it
less overwhelming. It's easier to figure out what's going on, which helps
when you're building or fixing things.
Work together better - Teams can work on different parts at the same
time. This means you can finish big projects faster.
Neater projects - Putting related stuff together in modules makes your
project more organized. This helps when you're dealing with a lot of
code.
Modular Programming in Industry
TinyMCE breaks down the editing process into over 30 specific modules
for different tasks. This makes it quick to set up different versions of their
editor.
Amazon designed Polly, their talking text service, with modules so you
can change how it speaks easily.
Spotify uses a similar idea but for their teams, allowing them to work on
small parts of the app independently. This helps them make changes
faster.
Top-Down Design
Top-Down Design is a problem-solving approach that starts with the highest-
level overview of a system and progressively breaks it down into smaller, more
manageable components. In Python, this method can be particularly effective
for structuring your code in a clear and organized manner.
PYTHON Modules
# calculator.py
import math_operations
def main():
print("Simple Calculator")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = input("Enter operation (+, -, *, /): ")
if operation == '+':
result = math_operations.add(num1, num2)
elif operation == '-':
result = math_operations.subtract(num1, num2)
elif operation == '*':
result = math_operations.multiply(num1, num2)
elif operation == '/':
result = math_operations.divide(num1, num2)
else:
result = "Invalid operation!"
print("Result:", result)
main()
Benefits of Using Modules
Code Reusability: Functions can be reused across different programs
without rewriting code.
Organization: Code is organized into separate files, making it easier to
manage and maintain.
Collaboration: Different team members can work on different modules
without conflicts.
The json module is used to work with JSON data, allowing you to encode and
decode JSON.
Example:
import json
File Operations:
Opening a Text File
Read Text File
Write to Text File
Appending to a File
Closing a Text File
File Access Mode
The access mode parameter serves as the determinant of the specific
mode in which the file is to be opened, thereby dictating whether
operations such as reading, writing, appending, etc., are permissible. Here
is a list of the different modes of opening a file:
The functions in Python that allow to read and write to files:
read() : This function reads the entire file and returns a string
readline() : This function reads lines from that file and returns as a string.
It fetch the line n, if it is been called nth time.
readlines() : This function returns a list where each element is single line
of that file.
readlines() : This function returns a list where each element is single line
of that file.
write() : This function writes a fixed sequence of characters to a file.
writelines() : This function writes a list of string.
append() : This function append string to the file instead of overwriting
the file.
close(): This function closes the file and frees the memory space acquired
by that file.
Syntax
Example:
#open a file
o = open ('nl.txt') #it is a default mode, i.e. read only mode
To read a file in Python, the file must first be opened in the read mode.
If you want a read-only first line only, use readline (), and if you
want to read all the lines in the form of lines, use readlines ()
If you want to read a few characters of the file, use read (size)
Example:
#read a file
To create a new file, we have to open a file using one of the two parameters:
x: it will create a new empty text file iff there does not exist any file with the
same name; otherwise, it will throw an error
w: it will create a file, whether any file exists with the same or not, i.e., it will
not return an error if the same file name exists.
Example:
#create a file
nl = open ('nl.txt', 'x') # it will create a new empty file but will throw an error if
the same file name exists
nl = open ('nl.txt', 'w') # it will create a file but if the same file name exist it will
overwrite
write () method
Example:
Example:
nl = open('nl.txt', w)
nl.writelines('This is the first line\n', 'This is the second line\n', 'This is the third
line')
nl.close()
Once you are done with all the operations, you need to close the file correctly.
The close () commands will terminate all the resources and will free the
system
Example
#close a file
nl = open('nl.txt', 'r')
print(nl.read())
nl.close()
Exception Handling
Exception handling in Python is the process of responding to unexpected
errors that occur while a program is running.
The goal of exception handling is to prevent the program from crashing and to
allow the interpreter to execute the rest of the code.
three types of errors in Python:
1. Syntax or parsing errors
2. Runtime Errors [Your code may be syntactically correct, but if Python
encounters something it cannot handle during runtime, it will throw an
exception.]
3. Logical Errors [
Python Exceptions:
Exceptions are abnormal conditions that occur during program execution, such
as dividing by zero, adding incompatible types, or accessing a non-existent file.
Handling exceptions
Exceptions are handled using the try and except block. You can use multiple
except blocks to handle different types of exceptions.
Built-in exceptions
Python has many built-in exceptions, including ZeroDivisionError, TypeError,
FileNotFoundError, and ImportError.
Raising exceptions
You can also explicitly raise an exception if a certain condition occurs. To do
this, use the raise keyword.
The finally clause
The finally clause is an optional clause that executes regardless of whether an
exception occurs. It can be used to define clean-up actions.
Detailed View :
Syntax :
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# Execute if no exception
finally:
# Some code ....(always executed)
Simple example
# put unsafe operation in try block
try:
print("code start")
Output:
Enter a number: An error occurred: EOF when reading a line
Example:
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
finally:
print("This is finally block.")
except ZeroDivisionError:
print ("Division by 0")
finally:
print ("inside outer finally block")
Output:
An error occurred: Age must be 18 or above.
Interview purpose:
Both unit testing and exception handling are the core part of Python
programming that makes your code production-ready and error-proof. In this
topic, we have learned about exceptions and errors in Python and how to handle
them. Furthermore, we have learned about complex nested try-except blocks
and created custom exception blocks based on requirements.
These tools and mechanisms are essential, but most of the work is done through
simple `try` and `except` blocks. Where `try` looks for exceptions raised by the
code and `except` handles those exceptions.