Pretty simple question but I am making OOP code and I see there are about three methods to create something new. First is the roblox method which is just object.new()
and then you configure the properties after that. Then there is object.new(data1,data2,data3)
and finally there is ‘object.new(…)’ which one is the best method?
You’re supposed to fill in the variables you need / wish to use to construct the object.
If your object (such as a Matrix
class) takes in a variable amount of arguments you use the variadic notation “…”
If you know the amount of variables it needs then just define those.
It depends on whether or not you need information to create your object. You can’t use Instance.new without telling it exactly what kind of instance you want to make.
Hmm is there any situation where I should use the object.new()
over the other two methods since so far It seems like putting in parameters are the best method.
I’ll introduce a second method which I think is better, using a dictionary.
The issue with object.new(data1,data2,data3) are the parameters, it can get really long for certain objects and very painful just look at this fractal noise generator object, unless you made it and know the order of the parameters by heart.
function fractalNoiseGenerator(seed, amplitude, frequency, octaves, lacunarity, persistence)
And sometimes lua lsp cannot help you autofill and tell you what the parameters are:
No the name of that function isn’t going to help me Mr Roblox LSP. I put the module in replicated storage using get service.
Seems to only work for script.Modulescript, more helpful thanks.
My preference is to use a dictionary to store the optional properties in order to avoid long lines during construction, as simple as that:
local ConstraintsTemplate = {
["YawLeft"] = 5;
["YawRight"] = 5;
["ElevationAngle"] = 40;
["DepressionAngle"] = 40;
}
function TurretController.new(JointMotor6D , ConstraintsTable)
--vs
function TurretController.new(JointMotor6D , YawLeft,YawRight,DepressionAngle,ElevationAngle)
--Which do you prefer? Your choice.
Edit: Yep similar to @UnknownParabellum dictionary configuration style gang
Ok I actually never thought of this method before but it solves my issue of searching through the creation parameters.
Personally, I like to use something like this Object.new(config)
where config is a table.
That means I can update the class and the inputs it takes in without having to fix all the times I called Object.new
before
Config is structured something like this :
config: {
["InputParameter1"] = "yes",
["InputParameter2"] = "Yes",
}