Skip to content

Instantly share code, notes, and snippets.

@mosdevly
Last active July 18, 2019 14:22
Show Gist options
  • Save mosdevly/c5961b4c6943ac5268376bc16cb8017a to your computer and use it in GitHub Desktop.
Save mosdevly/c5961b4c6943ac5268376bc16cb8017a to your computer and use it in GitHub Desktop.
Examples for the SOLID principles
"""Open/Closed Principle
Example inspired by this wonderful piece here: http://joelabrahamsson.com/a-simple-example-of-the-openclosed-principle/
"""
# Area calculator: calculate area of a rectangle
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
# Calculate area of multiple rectangles
class AreaCalculator:
"""
Single Responsibility Principle
Every module, class, or function should have responsibility over a single part
of the functionality provided by the software.
User class handles one thing: the identity of a user. It's sole method does exactly 1 thing: changes the name property.
"""
class User:
id = 1;
name = '';
def updateName(newName):
this.name = newName
console.log('Name updated.')
"""Open/Closed Principle
Example inspired by this wonderful piece here: http://joelabrahamsson.com/a-simple-example-of-the-openclosed-principle/
"""
class Shape:
def area(self):
NotImplementedError('You must implement this method!')
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
import math
return (self.radius**2)*math.pi
class AreaCalculator:
def calculate(self, shapes):
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment