The Hard-Coded Notification Problem
In a naive implementation, the Subject (the YouTube Channel) has to manage its Observers (Subscribers) by hand. The result is code that is stiff and easy to break. The main job, uploading videos, gets buried under notification details.
1. Understanding the Issue
Imagine we’re building a simple YouTube-like Notification System. Whenever a creator uploads a new video, all their subscribers should get notified. In the current design, the YoutubeChannel class must know exactly who is subscribed and how to reach each person. In the code, uploadNewVideo prints an email line and an in-app line, one for each subscriber, written straight into the method.
2. What’s Wrong with This Approach?
Tightly Coupled Code
- The Issue: The
YoutubeChannelclass itself decides how users are notified. - The Impact: If tomorrow we want to send an SMS or push notification, we have to edit the main
uploadNewVideomethod. The "What" (uploading) is glued to the "How" (notifying).
Violation of Single Responsibility Principle (SRP)
- The Issue: The class does two jobs: it handles video uploads and it handles how users are contacted.
- The Impact: The channel should only care about the video. Because it also handles email addresses and notification types, the class grows large and is hard to test.
Violation of Open/Closed Principle (OCP)
- The Issue: The class has to be changed again and again. Every time a new user clicks the "Subscribe" button, a developer must add a new line of code to the
YoutubeChannelclass. - The Impact: Code should be open for extension but closed for modification, meaning you add features without editing working code. This design breaks that rule every time.
No Runtime Flexibility (Scalability Issues)
- The Issue: Subscribers are hard-coded into the method.
- The Impact: A user cannot "Unsubscribe" or change how they are notified while the program runs. With hundreds or thousands of users, you would be editing code all the time.
3. Structural Analysis
| Feature | Status | Observation |
|---|---|---|
| Dependency | Rigid | The Channel depends on concrete email addresses. |
| Logic | Hard-coded | Notifications are baked into the upload method. |
| Maintenance | High | Every subscriber change requires a code deployment. |
| Dynamic Behavior | Impossible | Users cannot join or leave while the app is running. |
4. Summary of the "Smell"
A "smell" is a sign in the code that something is off. Suppose a method does its main job and then calls several unrelated services by hand (email, in-app messages, logging). That points to a missing subscription mechanism.
The Observer Pattern fixes this by allowing the Channel to say: "I just uploaded a video; I don't care who is listening, but here is the update." Each observer then handles the "how" on its own.