DEV Community

Anna Zubova
Anna Zubova

Posted on

SOLID Programming (Part 2): Open/Closed Principle

‘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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
codbugs profile image
Coding Bugs

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.

def count_ocurrences(counter, localfile):
   content = return open(localfile, "r").read()
   return counter(content.split())

def count_and_word():
   '''this is the counter method to pass to the previous function'''

def count_or_word():
   '''another counter method'''
Enter fullscreen mode Exit fullscreen mode

This sample extends the functionality of the first function without modifying it. Same method, and different ways of counting words.

Collapse
 
gagomes profile image
Goncalo Gomes • Edited

Great article! A small nit:

content = return open(file, "r").read()

return here should be a typo, probably copied from the function in the example that follows.

Collapse
 
andrea809 profile image
andrea809

great article

Collapse
 
cayohenrique08 profile image
Cayo Rodrigues

good article! Thanks!

Collapse
 
yougigun profile image
Yougigun

I like the saying "Open/Closed Principle says that the code should be open for extension but closed for modification."