Polymorphism
Table of Contents
Introduction
Polymorphism is an Object-Oriented Programming (OOP) pattern, where the most important idea is objects of different types being treated as a common of a superclass or interface. This means that a system can interact with objects of various types through a single point of reference, which makes our code design flexible, and extensible.
Overview
Ultimately, it’s usage is up to preference, but generally, we use it when we have a set of classes with related functionality but variations in behavior. Or when we want an extensible design, but it’s closed for modification.
As with any solution, there are cases where it isn’t the best at what it’s trying to solve. Such as when performance is critical and you know exactly what type of object you’re dealing with. Then in that case, using direct method calls might be better. But for most cases, the readability and maintainability benefits outweigh this minor unnecessary overhead performance hit.
Another case to be cautious of would be using the design pattern to prematurely optimize by forcing polymorphism if there’s minimal variation or when your code is simple. This would have the opposite effect; makes the code less readable.
Javascript
;
// Abstract base class for Search
// Abstract base class for SearchResult
// Concrete class for AuthorResult
// Concrete class for Author Search
;
Above, we’re utilizing inheritance and polymorphism to create a flexible search system for authors using the Open Library API. It begins with defining abstract base classes Search
and SearchResult
. These set the structure for the search operations and search results.
The concrete classes AuthorSearch
and AuthorResult
inherit from these base classes, enabling specific author searches and handling of author search results. The AuthorSearch
class overrides the performSearch()
method to query the Open Library API for author data, while AuthorResult
overrides the getInfo()
method to extract relevant information.
Above, Polymorphism is breaking the inheritance in a class by overriding certain methods. Polymorphism is seen in the dynamic invocation of performSearch()
and getInfo()
depending on the context of author search and the result retrieval.
The main function main()
orchestrates the search process, prompting the user for author names, displaying results, and storing selected author information using the implemented polymorphic methods.
PHP
Find Your Favorite Authors
Find Authors
Search
<?php
// Define an interface for polymorphism
interface Displayable {
public function display();
}
// Class representing an Author
class Author implements Displayable {
public $name;
function __construct($name) {
$this->name = $name;
}
public function display() {
echo " " . $this->name . " ";
}
}
// Class representing Search functionality
class Search implements Displayable {
public $results;
function __construct($searchResults) {
$this->results = $searchResults->docs;
}
public function display() {
if (count($this->results) > 0) {
echo " Search Results ";
foreach ($this->results as $result) {
$author = new Author($result->name);
$author->display();
}
echo " ";
} else {
echo "No authors found for your search.";
}
}
}
// Check if search parameter exists and is at least 3 characters long
if (isset($_GET['search']) && strlen($_GET['search']) >= 3) {
$searchQuery = urlencode(str_replace(" ", "%20", $_GET['search'])); // Encode search and spaces
$searchResults = json_decode(file_get_contents("https://openlibrary.org/search/authors.json?q=" . $searchQuery));
// Create a Search object and display results
$search = new Search($searchResults);
$search->display();
}
?>
Above, similar to the previous examples, we’re implementing inheritance and polymorphism to display the search results of authors from the Open Library database. The example is a bit brief because the page would reload whenever an HTTP request is sent or an action is triggered; both actions reload the browser page, and I didn’t want to utilize JavaScript to prevent the page from reloading. I wanted the example to be standalone PHP and HTML.
Anyway, there’s an interface named Displayable
with a method display()
, ensuring that any class implementing this interface provides a display functionality. The Author
class implements this interface to display individual author names. Another class, Search
, also implements Displayable
and is responsible for displaying search results.
Then, in the Search
class, it checks if search results exist and then iterates through each result, creating an Author
object for each and invoking its display()
method.
Python
=
=
return f
= # List to store published works (future implementation)
= # Changed to collect People (base class)
=
# Changed to search_people for broader use
=
continue
=
= +
=
=
break
# Changed to display_people for broader use
=
= - 1
# Create Author object only if person type is author (polymorphism)
=
return
=
=
break
Above, we’re defining three classes; Person
, Author
, and AuthorSearch
. The Person
class serves as the base class with attributes name
and key
, while Author
inherits from Person
, adding a published_works
list attribute for future implementation. The AuthorSearch
class utilizes polymorphism by accepting both Person
and Author
instances in its collected_people
list.
In the search_people
method, it searches for people based on user input, displaying the results and allowing the user to save selected authors to the collection. If the selected person is identified as an author, a corresponding Author
object is created and added to the collection.
Just like our previous example, this demonstrates polymorphism as the Author
class is used in place of the Person
class when appropriate. Moreover, the view_collection
method iterates over the collected people, displaying their details, showcasing inheritance with Person
and Author
instances treated uniformly.
As always, I hope you have a great day!