Lesson 6
Combining OOP Principles in JavaScript: Real-World Solutions
Introduction and Lesson Goal

Today's mission involves using multiple Object-Oriented Programming (OOP) principles to tackle complex tasks. When principles like Encapsulation, Abstraction, Polymorphism, and Composition are blended, the resulting code becomes streamlined and easier to manage.

Our goal is to dissect two real-world examples, gaining insights into how these principles can seamlessly orchestrate solutions.

Real-life Example 1: Building an Online Library System

Let's design an online library system, as we aim to reinforce our understanding of Encapsulation and Polymorphism. Encapsulation will help us protect the attributes of books, members, and transactions, making sure they are accessible in a controlled manner. Polymorphism will demonstrate its power by enabling a single interface to represent different underlying forms, such as digital and print versions of books.

JavaScript
1// Base class for different types of library users 2class Member { 3 constructor(name) { 4 this.name = name; 5 } 6 7 checkOutBook(book) { 8 console.log(`${this.name} checked out ${book.getBookType()} book ${book.title}.`); 9 } 10} 11 12// Base class for different types of books 13class Book { 14 constructor(title) { 15 this.title = title; 16 } 17 18 getBookType() { 19 // Abstract method to be overridden by subclasses 20 throw new Error("Subclass must implement abstract method"); 21 } 22} 23 24// Inherits from Book, represents a digital book 25class DigitalBook extends Book { 26 getBookType() { 27 return "Digital"; 28 } 29} 30 31// Inherits from Book, represents a physical book 32class PhysicalBook extends Book { 33 getBookType() { 34 return "Physical"; 35 } 36} 37 38// Library class that manages members and books 39class Library { 40 constructor() { 41 this.members = []; 42 this.books = []; 43 } 44 45 addMember(member) { 46 this.members.push(member); 47 } 48 49 addBook(book) { 50 this.books.push(book); 51 } 52} 53 54const myLibrary = new Library(); 55 56const alice = new Member("Alice"); 57const bob = new Member("Bob"); 58 59myLibrary.addMember(alice); 60myLibrary.addMember(bob); 61 62const digitalBook = new DigitalBook("The JavaScript Handbook"); 63const physicalBook = new PhysicalBook("Learning JavaScript Design Patterns"); 64 65myLibrary.addBook(digitalBook); 66myLibrary.addBook(physicalBook); 67 68alice.checkOutBook(digitalBook); // Prints: Alice checked out Digital book The JavaScript Handbook. 69bob.checkOutBook(physicalBook); // Prints: Bob checked out Physical book Learning JavaScript Design Patterns.

In this code snippet, Encapsulation is observed clearly through the class structures and the controlled access to their attributes. Polymorphism is vividly illustrated by how both DigitalBook and PhysicalBook classes inherit from the Book class but provide their own implementations of the getBookType method. This setup allows objects of DigitalBook and PhysicalBook to be used interchangeably when a book's type needs to be identified, demonstrating polymorphism's capability to work with objects of different classes through a common interface.

  • Encapsulation ensures that details about members and books are well-contained within their respective classes.
  • Polymorphism showcases flexibility by treating different book types uniformly, making the system more adaptive and scalable.
Real-life Example 2: Building a Shape Drawing Application

Next, we'll develop a shape-drawing application capable of drawing various shapes. For this, we'll employ the principles of Abstraction and Composition.

  • Abstraction simplifies the complexity associated with drawing different shapes.
  • Composition takes care of composite shapes.

Here's how we translate these principles into our shape-drawing application:

JavaScript
1// Define the basic Shape class 2class Shape { 3 // Abstract method that will be implemented in each subclass 4 draw() { 5 throw new Error("Subclass must implement abstract method"); 6 } 7} 8 9// Define the Circle class 10class Circle extends Shape { 11 // Implement the draw method for circle 12 draw() { 13 console.log("Drawing a circle."); 14 } 15} 16 17// Define the Square class 18class Square extends Shape { 19 // Implement the draw method for square 20 draw() { 21 console.log("Drawing a square."); 22 } 23} 24 25// Define the ShapeComposite class 26class ShapeComposite extends Shape { 27 // Initialize with an empty list of shapes 28 constructor() { 29 super(); 30 this.shapes = []; 31 } 32 33 // Add a new shape to the composite 34 addShape(shape) { 35 this.shapes.push(shape); 36 } 37 38 // Implement the draw method to draw each shape in composite 39 draw() { 40 for (const shape of this.shapes) { 41 shape.draw(); 42 } 43 } 44} 45 46const circle = new Circle(); 47const square = new Square(); 48 49// Drawing individual shapes 50circle.draw(); // Output: Drawing a circle. 51square.draw(); // Output: Drawing a square. 52 53// Create a ShapeComposite instance for composite shapes 54const compositeShape = new ShapeComposite(); 55 56// Add individual shapes to the composite 57compositeShape.addShape(circle); 58compositeShape.addShape(square); 59 60// Drawing the composite shape 61compositeShape.draw(); 62/* 63Output: 64Drawing a circle. 65Drawing a square. 66*/

This example unveils how Abstraction streamlines the process of drawing different shapes and Composition handles complex shapes.

Lesson Summary and Practice

Well done! You combined multiple OOP principles to respond to complex tasks. By dissecting real-world examples, we understood how these principles found their applications. Now, it's time to put this knowledge to work. Practice fortifies concepts, transforming knowledge into expertise. So, let's get coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.