Rules Hub
Coding Rules Library
Push subclass-specific logic down from base classes
Avoid defining methods in an abstract base class if they are only used by specific subclasses.
Bad example
| 1 | abstract class BaseNotification { |
| 2 | abstract send(): void; |
| 3 |
|
| 4 | // BAD: This logic is specific to Email, but exposed to SMS too |
| 5 | protected formatEmailSubject(subject: string): string { |
| 6 | return `[Urgent] ${subject}`; |
| 7 | } |
| 8 | } |
| 9 |
|
| 10 | class SMSNotification extends BaseNotification { |
| 11 | send() { |
| 12 | // SMS inherits formatEmailSubject unnecessarily |
| 13 | } |
| 14 | } |
Explanation (EN)
The base class contains methods that are only relevant to one specific subclass. This pollutes the interface of other subclasses (like SMSNotification) with unrelated logic and violates separation of concerns.
Objašnjenje (HR)
Bazna klasa sadrži metode koje su relevantne samo za jednu specifičnu podklasu. To zagađuje sučelje drugih podklasa (poput SMSNotification) nepovezanom logikom i narušava odvajanje odgovornosti.
Good example
| 1 | abstract class BaseNotification { |
| 2 | abstract send(): void; |
| 3 | } |
| 4 |
|
| 5 | class EmailNotification extends BaseNotification { |
| 6 | // GOOD: Logic exists only where it is needed |
| 7 | private formatSubject(subject: string): string { |
| 8 | return `[Urgent] ${subject}`; |
| 9 | } |
| 10 |
|
| 11 | send() { |
| 12 | const subject = this.formatSubject("Alert"); |
| 13 | // send email... |
| 14 | } |
| 15 | } |
| 16 |
|
| 17 | class SMSNotification extends BaseNotification { |
| 18 | send() { |
| 19 | // Clean class without email-specific methods |
| 20 | } |
| 21 | } |
Explanation (EN)
The specific logic is moved down into the subclass that actually needs it. The base class remains generic and clean, ensuring that siblings (like SMSNotification) are not burdened with unused methods.
Objašnjenje (HR)
Specifična logika premještena je u podklasu koja je stvarno treba. Bazna klasa ostaje generička i čista, osiguravajući da srodne klase (poput SMSNotification) nisu opterećene metodama koje ne koriste.