⬅ Previous Topic
Writing Readable CodeNext Topic ⮕
Version Control Basics⬅ Previous Topic
Writing Readable CodeNext Topic ⮕
Version Control BasicsCode reusability means writing code in a way that it can be reused in multiple places without rewriting it. This improves maintainability, reduces errors, and saves time during development.
For example, instead of copying and pasting the same logic in different parts of the program, we can define it once as a function or module and reuse it wherever needed.
The DRY principle stands for "Don't Repeat Yourself". It encourages programmers to reduce repetition in code. Every piece of knowledge should have a single, unambiguous representation within a system.
# Pseudocode to print area of a rectangle at two places
length1 = 5
breadth1 = 10
area1 = length1 * breadth1
print("Area 1:", area1)
length2 = 3
breadth2 = 7
area2 = length2 * breadth2
print("Area 2:", area2)
Output:
Area 1: 50 Area 2: 21
The logic to calculate area is repeated. If you later want to change the formula or add validation, you’ll need to update it in multiple places.
# Function to calculate area of rectangle
function calculateArea(length, breadth):
return length * breadth
# Using function to calculate different areas
area1 = calculateArea(5, 10)
print("Area 1:", area1)
area2 = calculateArea(3, 7)
print("Area 2:", area2)
Output:
Area 1: 50 Area 2: 21
We defined the formula once inside the calculateArea
function and reused it. This makes the code shorter, more readable, and easier to maintain.
What if you want to log a warning if either length or breadth is zero?
With the DRY approach, you only need to modify the calculateArea
function. All usages benefit automatically from this update:
function calculateArea(length, breadth):
if length == 0 or breadth == 0:
print("Warning: One of the dimensions is zero!")
return length * breadth
Consider a scenario where we want to calculate areas for many rectangles stored in a list. Instead of repeating code for each one, we can loop through and reuse our function:
rectangles = [(4, 5), (6, 2), (3, 7)]
for each rect in rectangles:
length = rect[0]
breadth = rect[1]
area = calculateArea(length, breadth)
print("Area:", area)
Output:
Area: 20 Area: 12 Area: 21
Applying the DRY principle and aiming for code reusability are essential for writing professional-grade code. Always look for opportunities to refactor repeated code into reusable components like functions or modules.
After writing a block of code, ask yourself: "Will I need this logic again?" If yes, turn it into a function!
⬅ Previous Topic
Writing Readable CodeNext Topic ⮕
Version Control BasicsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.