SE Lab
0 0

خمسة مبادئ، خمس حالات حقيقيةFive principles, five real cases

لكل مبدأ: صورة من الحياة، رسم بالأشكال، ثم الكود قبل وبعد. اختر لغتك المفضّلة من الأزرار فوق الكود.For each principle: an everyday photo, a drawing with shapes, then the code before and after. Pick your language with the buttons above the code.

0 / 5
S

خدمة الطلبات التي تفعل كل شيءThe order service that does everything

متجر إلكتروني: عند إتمام الطلب نحسب المجموع، نحفظ الطلب، ونرسل بريد التأكيد. كل ذلك في دالة واحدة.An online store: placing an order computes the total, saves the order and emails a confirmation. All in one method.

المسؤولية الواحدة · Single Responsibility e-commerce service repository
سكين سويسري مفتوح بكل أدواته · A Swiss Army knife with every tool open
أداة تفعل كل شيء… ولا تتقن شيئًا. وإن انكسر جزء، تعطّل الكل.One tool that does everything… and nothing well. Break one part and the whole thing goes to repair. Jonas Bergsten · Public domain · Wikimedia Commons

قبلBefore

class OrderService {
  placeOrder(cart, user) {
    // 1) business rule
    const total = cart.items.reduce((sum, i) => sum + i.price, 0);
    // 2) database
    db.query('INSERT INTO orders ...', [user.id, total]);
    // 3) email
    smtp.send(user.email, 'Order confirmed', `Total: ${total}`);
  }
}
  • اسم الصنف فيه Manager أو Service ويكبر بلا حدود.The class is called Manager or Service and keeps growing.
  • أشخاص من فرق مختلفة يعدّلون نفس الملف.People from different teams edit the same file.

بعدAfter

class OrderService {
  constructor(orders, mailer) {
    this.orders = orders;
    this.mailer = mailer;
  }

  placeOrder(cart, user) {
    const total = cart.total();
    this.orders.save(user.id, total);        // OrderRepository: database only
    this.mailer.orderConfirmed(user, total); // OrderMailer: email only
  }
}
  • تغيير البريد لا يلمس كود قاعدة البيانات.Changing the email never touches the database code.
  • كل جزء يُختبر وحده.Each part can be tested on its own.

بعد الفصل، من يعرف جملة SQL؟After the split, who knows the SQL statement?

O

طرق الدفع التي لا تنتهيPayment methods that never stop coming

تطبيق توصيل: بدأ بالبطاقة، ثم PayPal، والآن Apple Pay. كل طريقة جديدة تفتح نفس الدالة.A delivery app: it started with cards, then PayPal, now Apple Pay. Every new method reopens the same function.

مفتوح / مغلق · Open / Closed payments strategy interface
مكعبات ليغو ملوّنة · Colourful Lego bricks
تضيف قطعة جديدة دون أن تقصّ القطع القديمة.You add a new brick without cutting the old ones. Alan Chia · CC BY-SA 2.0 · Wikimedia Commons

قبلBefore

function pay(method, amount) {
  if (method === 'card') {
    return chargeCard(amount);
  } else if (method === 'paypal') {
    return chargePaypal(amount);
  }
  // Apple Pay next month? Open this function and edit it again...
}
  • if / else أو switch على «النوع» يتكرّر في عدة أماكن.An if / else or switch on “type” repeated in several places.
  • كل ميزة جديدة تبدأ بـ «افتح الملف القديم».Every new feature starts with “open the old file”.

بعدAfter

class CardPayment   { pay(amount) { /* ... */ } }
class PaypalPayment { pay(amount) { /* ... */ } }
class ApplePay      { pay(amount) { /* ... */ } } // new class, old code untouched

function checkout(method, amount) {
  return method.pay(amount); // never changes again
}
  • ميزة جديدة = ملف جديد.A new feature = a new file.
  • الكود القديم المُختبَر يبقى كما هو.Old tested code stays exactly as it is.

ماذا يتغيّر في checkout عند إضافة Google Pay؟What changes in checkout when Google Pay is added?

L

الاشتراك الذي لا يُلغىThe subscription that cannot be cancelled

تطبيق بثّ: اشتراك شهري واشتراك مدى الحياة. زر «إغلاق الحساب» يلغي كل الاشتراكات… وينهار.A streaming app: monthly and lifetime plans. The “close account” button cancels every subscription… and crashes.

استبدال ليسكوف · Liskov Substitution inheritance subscriptions contract
بطة مطاطية في وعاء زجاجي · A rubber duck in a glass bowl
تشبه البطة، لكن هل تستطيع أن تفعل كل ما تفعله البطة؟It looks like a duck, but can it do everything a duck does? Nanda93 · Public domain · Wikimedia Commons

قبلBefore

class Subscription {
  cancel() { this.active = false; }
}

class LifetimeSubscription extends Subscription {
  cancel() { throw new Error('Lifetime plans cannot be cancelled'); }
}

// Fine with the parent, crashes with the child:
function closeAccount(subscriptions) {
  subscriptions.forEach((s) => s.cancel());
}
  • دالة في الابن ترمي «غير مسموح» أو تُترك فارغة.A child method throws “not allowed” or is left empty.
  • فحص النوع قبل النداء: if (x instanceof …).Type checks before a call: if (x instanceof …).

بعدAfter

class Subscription { /* shared: owner, price */ }

class MonthlySubscription extends Subscription {
  cancel() { this.active = false; }
}

class LifetimeSubscription extends Subscription { /* no cancel() at all */ }

// Asks only for the type that really can be cancelled:
function closeAccount(monthlySubscriptions) {
  monthlySubscriptions.forEach((s) => s.cancel());
}
  • الدالة تطلب فقط النوع الذي يدعم ما تريده.The function asks only for the type that supports what it needs.
  • الخطأ يُكتشف وقت الكتابة، لا عند المستخدم.The mistake shows up while coding, not in front of the user.

لماذا ينهار closeAccount في النسخة الأولى؟Why does closeAccount crash in the first version?

I

بوّابة الدفع السمينةThe fat payment gateway

واجهة واحدة لكل بوّابات الدفع فيها تحصيل واسترداد واشتراك. «الدفع عند الاستلام» لا يعرف إلا التحصيل.One interface for every gateway with charge, refund and subscribe. Cash on delivery only knows how to charge.

فصل الواجهات · Interface Segregation interfaces payments roles
جهاز تحكم تلفاز بأزرار كثيرة · A TV remote with many buttons
تريد زرّ الصوت فقط، لكنك مجبر على حمل كل هذه الأزرار.You only want the volume button, but you are forced to carry all of these. Raimond Spekking · CC BY-SA 4.0 · Wikimedia Commons

قبلBefore

// One big "contract": every gateway must have all three methods
class CashOnDelivery {
  charge(order)   { /* collect cash at the door */ }
  refund(order)   { throw new Error('Not supported'); }
  subscribe(plan) { throw new Error('Not supported'); }
}
  • دوال ترمي «Not supported».Methods that throw “Not supported”.
  • واجهة فيها أكثر من 5 دوال غير مترابطة.An interface with more than 5 unrelated methods.

بعدAfter

// Small roles: Chargeable, Refundable, Subscribable
class CashOnDelivery {            // Chargeable
  charge(order) { /* ... */ }
}

class StripeGateway {             // Chargeable + Refundable + Subscribable
  charge(order)   { /* ... */ }
  refund(order)   { /* ... */ }
  subscribe(plan) { /* ... */ }
}
  • كل صنف يَعِد فقط بما يستطيع فعله.Each class promises only what it can do.
  • تغيير «الاشتراك» لا يؤثر على «الدفع عند الاستلام».Changing “subscribe” never affects cash on delivery.

أي أدوار يحتاجها CashOnDelivery؟Which roles does CashOnDelivery need?

D

الإشعارات الملتصقة بـ FirebaseNotifications glued to Firebase

تطبيق تسوّق يرسل إشعار «طلبك في الطريق». الصنف ينشئ عميل Firebase بنفسه، فلا يمكن تبديله أو اختباره.A shopping app sends “your order is on the way”. The class creates the Firebase client itself, so it cannot be swapped or tested.

عكس الاعتمادية · Dependency Inversion dependency injection push testing
مكواة موصولة بمقبس الجدار · An iron plugged into a wall socket
المكواة تعتمد على شكل المقبس (العقد)، لا على محطة الكهرباء.The iron depends on the socket shape (the contract), not on the power station. Meganbeckett27 · CC BY-SA 3.0 · Wikimedia Commons

قبلBefore

class OrderNotifier {
  constructor() {
    this.push = new FirebaseClient(); // glued to one vendor
  }

  shipped(order) {
    this.push.send(order.userId, 'Your order is on the way');
  }
}
  • كلمة new لصنف خارجي داخل منطق العمل.The word new on an external class inside business logic.
  • الاختبار يحتاج إنترنت أو قاعدة بيانات حقيقية.A test needs the internet or a real database.

بعدAfter

class OrderNotifier {
  constructor(sender) {          // any object that has send()
    this.sender = sender;
  }

  shipped(order) {
    this.sender.send(order.userId, 'Your order is on the way');
  }
}

new OrderNotifier(new FirebaseSender()); // production
new OrderNotifier(new FakeSender());     // tests: no network needed
  • تبديل المزوّد = صنف جديد واحد.Swapping the vendor = one new class.
  • اختبار سريع بمرسل وهمي (FakeSender).Fast tests with a FakeSender.

ماذا نمرّر في الاختبار؟What do we pass in during a test?