Skip to content

Instantly share code, notes, and snippets.

@utkarshsingh99
Created April 17, 2024 14:26
Show Gist options
  • Save utkarshsingh99/6fa7634fe324d60a96f6115d1779465e to your computer and use it in GitHub Desktop.
Save utkarshsingh99/6fa7634fe324d60a96f6115d1779465e to your computer and use it in GitHub Desktop.
Updated gist that fixes the problematic code for robot hierarchy
# The ReadingRobot class incorrectly attempts to implement
# the clean_room method, which is specific to CleaningRobot
# and not applicable to ReadingRobot.
# This violates the principle of inheritance, where subclasses
# should override methods only when they are meant to provide a
# different implementation.
# To fix this, we can redesign the class hierarchy to separate
# the common behavior from the specific behavior more clearly.
# One approach is to use composition instead of inheritance,
# where classes have references to objects that implement the
# shared behavior.
# A module containing shared behavior for robots
module RobotBehavior
def move(x, y)
motor_x(x)
motor_y(y)
end
end
# A class representing a robot that cleans things
class CleaningRobot
include RobotBehavior
def clean_room(room_name)
coordinates = find_room(room_name)
move(coordinates.x, coordinates.y)
initiate_cleaning
end
end
# A class representing a robot that reads books
class ReadingRobot
include RobotBehavior
def read_book(book_title)
# Logic to read a book
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment