Software architecture and design patterns
A good architecture splits a program into parts that each have a clear role: for example the display, the business logic and data access. This is separation of concerns: you can change one part without breaking the others, and test each one separately.
Design patterns are proven solutions to common problems. Strategy passes the behaviour as a parameter (a function or an object); Observer automatically notifies subscribers when something changes; Factory creates the right object based on a parameter; Singleton guarantees that only one instance of a class exists.
class Newsletter:
def __init__(self):
self.subscribers = []
def subscribe(self, callback):
self.subscribers.append(callback)
def publish(self, article):
for notify in self.subscribers:
notify(article)
news = Newsletter()
news.subscribe(lambda a: print("Email sent:", a))
news.subscribe(lambda a: print("Push sent:", a))
news.publish("New Python course")
def make_area(kind):
formulas = {"square": lambda s: s * s, "circle": lambda r: 3.14 * r * r}
return formulas[kind]
print(make_area("square")(4))