الدرس 5.2 · الكود والأرقام⏱ 12 دقيقة
الفصل 5: SOLID: خمس قواعد لكود بيتغير بسهولة
تجربة: SMS ولا WhatsApp؟
الأكاديمية بتبعت رسالة لما الطالب يغيب، وعايزين نغيّر الطريقة ونختبر من غير رسايل حقيقية.
- AttendanceService بياخد Notifier في الـ constructor.
- SMS و WhatsApp واختبار: من غير ما نلمس الكود الأصلي.
- ده اسمه Dependency Injection.
الشرح بالتفصيل
AttendanceService بيعمل new SmsNotifier() جواه، فهو مربوط بيه للأبد. بعده: الاتنين بيعتمدوا على الـ interface، واتجاه الاعتماد «اتقلب».import java.util.*;
interface Notifier { void send(String to, String msg); } // «العقد» بس
class SmsNotifier implements Notifier {
public void send(String to, String msg) { System.out.println("[SMS → " + to + "] " + msg); }
}
class WhatsAppNotifier implements Notifier {
public void send(String to, String msg) { System.out.println("[WhatsApp → " + to + "] " + msg); }
}
class FakeNotifier implements Notifier { // للاختبار: بيسجل بس
final List<String> sent = new ArrayList<>();
public void send(String to, String msg) { sent.add(to + ": " + msg); }
}
class AttendanceService {
private final Notifier notifier; // بيعتمد على الـ interface
AttendanceService(Notifier n) { this.notifier = n; } // حد تاني بيختار التنفيذ
void markAbsent(String student, String parentPhone) {
notifier.send(parentPhone, student + " was absent today");
}
}
public class Notify {
public static void main(String[] a) {
new AttendanceService(new SmsNotifier()).markAbsent("Ali", "0100…");
new AttendanceService(new WhatsAppNotifier()).markAbsent("Mona", "0111…");
var fake = new FakeNotifier();
new AttendanceService(fake).markAbsent("Omar", "0122…");
System.out.println("test: " + (fake.sent.equals(List.of("0122…: Omar was absent today")) ? "PASS" : "FAIL"));
}
}
النتيجة:
[SMS → 0100…] Ali was absent today [WhatsApp → 0111…] Mona was absent today test: PASS
الـ 3 احتياجات اتحلوا ومحدش لمس AttendanceService. وتمرير الـ dependency من برا (في الـ constructor) اسمه Dependency Injection. الـ frameworks الكبيرة زي Spring وظيفتها الأساسية إنها تعمل ده أوتوماتيك لآلاف الـ classes.
ملاحظةدوس «☕ افتح في روبو كود» وشغّل الكود في المتصفح وغيّر فيه. وفي برنامج روبو لاب على الكمبيوتر فيه كمان «🖥 شغّل على الجهاز» على Java الحقيقية (JVM).

