Hey DevForum members,
I hope you’re keeping well.
In an attempt to make my Car
class as versatile as possible, I want it to be able to adapt to missing properties.
I want to make property dependant methods inaccessible if we weren’t able to get the information we need upon construction.
The code below is purely to illustrate a use case. It works, but I know there’s a smarter solution out there.
Summary:
- Constructor called
-
newcar:_propogateLightGroups()
returnsnil
newcar.Lights = nil
-
_failsafe()
is moved inside the object and replacessetHeadlightState()
as a direct reference
Car = {}
Car.__index = Car
-- Constructor. Returns a bus object.
function Car.new(carModel)
local newcar = {}
setmetatable(newcar, Car)
newcar.Model = carModel
-- Assume this returns nil.
newcar.Lights = newcar:_propogateLightGroups()
-- Let's make the method inaccessible if we don't have what we need.
if not newcar.Lights then
newcar.setHeadlightState = newcar._failsafe
end
return newcar
end
function Car:_failsafe()
warn("The method was unable to execute due to missing properties.")
end
function Car:setHeadlightState(state)
print("Headlights: ", state)
end
return Car
The Ideal Solution
Right now I’m unsure of how I could pass through additional values when remapping the method in my constructor. Being able to do this would be amazing.
function Car:_failsafe(func)
warn(func or "undefined_function", " was unable to execute due to missing properties.")
end
What I’ve Considered
This too, would work. By adding a presence check in the method itself I could avoid things going wrong down the line. But it goes against the philosophy of writing repeatable code, and ideally I’d be able to avoid the method being called altogether.
function Car:setHeadlightState(state)
if not self.Lights then self:_failsafe("setHeadlightState()") return end
print("Headlights: ", state)
end
Thoughts, concerns and ideas are all appreciated. Thanks in advance!