‘O’ in SOLID stands for Open/Closed Principle. It is closely related to the Single Responsibility Principle as code written with Single Responsibility in mind tends to comply with the Open/Closed Principle too.
Open/Closed Principle says that the code should be open for extension but closed for modification. In other words, the code should be organized in such a way that new modules can be added without modifying the existing code.
Let’s look at an example of the function that counts words in a text after extracting it in a local file:
def count_word_occurrences(word, localfile):
content = return open(file, "r").read()
counter = 0
for e in content.split():
if word.lower() == e.lower():
counter += 1
return counter
But what if we wanted to extract content from other source, like for example a url? If we worked with the above function, to implement new functionality, we would need to modify the existing function which would go against the Open/Closed Principle.
The better way of organizing the code would be the following:
def read_localfile(file):
'''Read file'''
return open(file, "r").read()
def count_word_occurrences(word, content):
'''Count number of word occurrences in a file'''
counter = 0
for e in content.split():
if word.lower() == e.lower():
counter += 1
return counter
This way, if we wanted to add reading from url functionality, we would just add the function that extracts text from url:
from bs4 import BeautifulSoup
from urllib.request import urlopen
def get_text_from_url(url):
'''Extract html as string from given url'''
page = urlopen(url).read()
soup = BeautifulSoup(page)
text = soup.get_text()
return text
Next we would just call the already existing function count_word_occurrences()
with the content extracted using get_text_from_url()
function:
content = get_text_from_url('https://en.wikipedia.org/wiki/Main_Page')
count_word_occurrences('and', content)
So we added new functionality to the code without needing to modify the existing code.
Code in GitHub
You can find the code for this article in this GitHub repository:
https://github.com/AnnaLara/SOLID_blogposts
Top comments (5)
I don't think the code of this article shows what this principle is about. I think you are changing your code but not extending it.
Let me share what I would do with your sample. My starting point will be the first code and the adaptation to this principle will be to pass a method as an argument that do anything with the array of words.
This sample extends the functionality of the first function without modifying it. Same method, and different ways of counting words.
Great article! A small nit:
return
here should be a typo, probably copied from the function in the example that follows.great article
good article! Thanks!
I like the saying "Open/Closed Principle says that the code should be open for extension but closed for modification."