What ?
Inheritance concept allows a class to inherit properties and behaviors from another class.
Why ?
Let's understand the necessity of inheritance and the problem that it solves using an example.
Task:
Build a website that allows users to view and handle their electricity account. It should have the below pages,
- Dashboard
- Account summary
- Payments page and more importantly the pages should be visible only to logged in user.
Find below some pseudo code that could achieve the task in hand,
Dashboard page:
class Dashboard {
login() {
// some logic to login the user
console.log(`User logged in successfully`);
}
}
const dashObj = new Dashboard();
dashObj.login();
Payments page:
class PaymentPage {
login() {
// some logic to login the user
console.log(`User logged in successfully`);
}
}
const payObj = new PaymentPage();
payObj.login();
AccountSummary page:
class AccountSummaryPage {
login() {
// some logic to login the user
console.log(`User logged in successfully`);
}
}
const accObj = new AccountSummaryPage();
accObj.login();
Problems:
Redundancy
: Each class repeats the same login() method. As the number of pages grows, so does the duplication of this logic.Maintainability: If the login logic changes, every class needs to be updated, increasing the risk of errors.
How to solve? (Inheritance to rescue)
We can solve the problem by extracting the common functionality (login) into a base class. The individual page classes will then inherit this functionality.
Parent/Base class:
class LoginParent {
login() {
// some logic to login the user
console.log(`User logged in successfully`);
}
}
Child classes inheriting the parent's method/members:
class DashboardChild extends LoginParent {}
class PaymentPageChild extends LoginParent {}
class AccountSummaryChild extends LoginParent {}
Usage:
const dash = new DashboardChild();
dash.login();
const pay = new PaymentPageChild();
pay.login();
const acc = new AccountSummaryChild();
acc.login();
Advantages:
- Reusability: The login() method is defined once in the base class and reused across all pages.
- Maintainability: Any updates to the login() logic need to be made only in the base class, reducing the scope for errors.
- Clarity: The code for each page focuses only on page-specific functionality, keeping the implementation clean and focused.
When to Use Inheritance?
Inheritance is useful when:
Classes share common functionality that is central to their behavior.
You want to adhere to the DRY (Don’t Repeat Yourself) principle.
You aim to create a hierarchical structure to represent relationships between entities.
Conclusion:
Inheritance simplifies code by promoting reusability and maintainability. By moving shared logic into a base class, we can eliminate redundancy, making the application easier to scale and manage.
Top comments (0)