1.1 - SOLID - תרגול
זיהוי הפרות¶
הקוד הבא מפר עקרון SOLID אחד לפחות. לכל קטע קוד - זהו איזה עקרון מופר והסבירו למה.
תרגיל 1¶
class UserManager:
def create_user(self, username: str, password: str):
import sqlite3
db = sqlite3.connect("app.db")
import hashlib
hashed = hashlib.sha256(password.encode()).hexdigest()
db.execute("INSERT INTO users VALUES (?, ?)", (username, hashed))
db.commit()
import smtplib
server = smtplib.SMTP("smtp.gmail.com")
server.sendmail("no-reply@app.com", username, "Welcome!")
print(f"User {username} created successfully")
תרגיל 2¶
from abc import ABC, abstractmethod
class ReportGenerator(ABC):
@abstractmethod
def generate_pdf(self): pass
@abstractmethod
def generate_excel(self): pass
@abstractmethod
def generate_html(self): pass
@abstractmethod
def send_by_email(self, email: str): pass
@abstractmethod
def save_to_disk(self, path: str): pass
class SimpleReport(ReportGenerator):
def generate_pdf(self):
return "PDF report"
def generate_excel(self):
raise NotImplementedError("Doesn't support Excel")
def generate_html(self):
raise NotImplementedError("Doesn't support HTML")
def send_by_email(self, email: str):
raise NotImplementedError("Doesn't send emails")
def save_to_disk(self, path: str):
with open(path, "w") as f:
f.write("PDF report")
תרגיל 3¶
class PaymentProcessor:
def process(self, payment_type: str, amount: float):
if payment_type == "credit_card":
print(f"Processing credit card: {amount}")
# Credit card logic
elif payment_type == "paypal":
print(f"Processing PayPal: {amount}")
# PayPal logic
elif payment_type == "bitcoin":
print(f"Processing Bitcoin: {amount}")
# Bitcoin logic
תיקון¶
בחרו אחד מהתרגילים למעלה ותקנו אותו כך שיעמוד בעקרונות SOLID.
TaskFlow¶
חזרו לקוד הפרויקט מהשיעור הקודם (0.2 - הפרויקט).
- זהו שלושה מקומות שמפרים עקרונות SOLID
- לכל מקום - ציינו איזה עקרון מופר ולמה