Is it a bad practice to create a child class of another child class?

I am somewhat unsure if this is the right place to post this question as it is not related to an issue I have, so please inform me if I should move it.

I have a question about inheritance when writing object-oriented code. Is it a bad practice to create a class that inherits another class that itself inherits a third? As in, create a child class of another child class.

Here is an example to further clarify (only for an example, not code I am planning to use):

-- First class, "grandparent"
Vehicle = {}
Vehicle.__index = Vehicle

function Vehicle.new()
    local vehicle = {}
    setmetatable(vehicle, Vehicle)

    vehicle.velocity = 0

    return vehicle
end

function Vehicle:boost()
    self.velocity = self.velocity + 5
end

-- Second class and child of first class
Car = {}
Car.__index = Car
setmetatable(Car, Vehicle)

function Car.new()
    local car = Vehicle.new()
    setmetatable(car, Car)

    return car
end

function Car:boost()
    print('The car is now boosting')
    Vehicle['boost'](self)
end

-- Third class and child of second class
Truck = {}
Truck.__index = Truck
setmetatable(Truck, Car)

function Truck.new()
    local truck = Car.new()
    setmetatable(truck, Truck)

    return truck
end

function Truck:boost()
    print('The truck is now boosting')
    Car['boost'](self)
end

Just to make it more clean in this case, you could use Vehicle class as a parent class for Truck.
If you need more advanced class structure though, you can have many classes inheriting from each other but keep in mind you should keep it simple.
You need to think over if it actually increases the code readability or only makes it more complicated.

I’m not a fan of implementing OOP in Lua at all - just because it usually defeats the purpose.

It’s only a bad practice if you’re unable to handle the entire class’s hierarchy, Roblox itself has many objects which inherit from objects that inherit from other objects.

Consider the inheritance path of SpawnLocation instances:
Instance > PVInstance > BasePart > FormFactorPart > Part > SpawnLocation

That’s a lot of layers of inheritance just to reach the final object, but it works.

2 Likes