OOP code correct?

I was just wondering if this OOP code is correct and if there is anything I can change about it? First time trying OOP.

ModuleScript:

local Train = {}
Train.__index = Train

function Train.NewTrain(number, color)
	local NewTrain = {}
	setmetatable(NewTrain, Train)
	
	NewTrain.number = number
	NewTrain.color = color
	
	print(number)
	print(color)
	
	return NewTrain
end

function Train:ChangeNumber(NewNumber)
	self.number = NewNumber
	print(NewNumber)
end

return Train

Script:

local TrainModule = require(game.ReplicatedStorage.OOPTrainModule)

NewTrain = TrainModule.NewTrain(1, "red")
NewTrain:ChangeNumber(7)

Output:
Screen Shot 2021-07-02 at 10.34.34 PM

Yeah that looks right. The only nitpicks I would make are on the naming convention of your variables and of the constructor but those are personally subjective so I’ll keep them to myself since they don’t actually affect the usability of your code.

The script on the other hand that requires and creates a train object does have one change I’d make though: make sure NewTrain is a local variable not a global. That has different technical implications, it’s better to use locals as much as possible throughout your code.

2 Likes