Understanding Software Abstractions: Is a Square a Rectangle?
Written on
Chapter 1: Introduction to Software Abstractions
The question of whether a square qualifies as a rectangle is one that many, including young children, can quickly answer: Yes, a square is indeed a type of rectangle, characterized by having all sides of equal length. However, this seemingly straightforward question can cause seasoned software developers to hesitate.
This discussion serves as a cautionary reminder that creating software abstractions can be challenging, even when they appear simple at first glance.
Section 1.1: The Square and Rectangle Dilemma
In the context of software development, an experienced developer might argue that a square should NOT be classified as a rectangle. The rationale behind this perspective is quite straightforward. Let's examine the class abstractions for both Rectangle and Square:
class Rectangle {
length: number;
width: number;
getArea(): number {
return this.length * this.width;}
}
class Square {
size: number;
getArea(): number {
return Math.pow(this.size, 2);}
}
These classes are fundamentally different. The Rectangle class has properties for both length and width, while the Square class has only a single property, size. Attempting to implement Square extends Rectangle or vice versa would violate important best practices, specifically the Liskov Substitution Principle from the SOLID principles, as well as the is-a relationship principle. Hence, we conclude that a square does NOT fit the definition of a rectangle.
Photo by Vincent LaVigna on Unsplash
Chapter 2: Real-World Considerations in Abstractions
To validate this solution, let's think about various shapes in the real world. For instance, a sphere is a shape with volume, while rectangles and squares do not possess this attribute. Thus, our abstraction might misrepresent certain characteristics.
It's crucial that our abstractions and their corresponding names reflect reality accurately.
In conclusion, while creating abstractions can be fraught with difficulty, it's important to remain mindful of naming conventions, adhere to best practices like SOLID principles, and accept some level of duplication until that enlightening moment strikes.
This video titled "Object-Oriented Design: Square-rectangle problem" delves deeper into the intricacies of this topic, highlighting the challenges faced in software design.
In the video "C++ - Lesson #44 - Object Oriented Programming Square Shapes Demo," viewers can observe practical demonstrations of these concepts in action.
Thank you for being part of our community! If you found this discussion valuable, please give it a thumbs up and consider following the author for more insights. Stay connected with us through our social media channels and newsletter for the latest updates and opportunities in the tech industry.