לדלג לתוכן

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, "ברוך הבא!")
        print(f"משתמש {username} נוצר בהצלחה")

תרגיל 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("לא תומך ב-Excel")

    def generate_html(self):
        raise NotImplementedError("לא תומך ב-HTML")

    def send_by_email(self, email: str):
        raise NotImplementedError("לא שולח מיילים")

    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"מעבד כרטיס אשראי: {amount}")
            # לוגיקה לכרטיס אשראי
        elif payment_type == "paypal":
            print(f"מעבד PayPal: {amount}")
            # לוגיקה ל-PayPal
        elif payment_type == "bitcoin":
            print(f"מעבד Bitcoin: {amount}")
            # לוגיקה ל-Bitcoin

תיקון

בחרו אחד מהתרגילים למעלה ותקנו אותו כך שיעמוד בעקרונות SOLID.

TaskFlow

חזרו לקוד הפרויקט מהשיעור הקודם (0.2 - הפרויקט).
- זהו שלושה מקומות שמפרים עקרונות SOLID
- לכל מקום - ציינו איזה עקרון מופר ולמה