Object Oriented Programming - The Way I Do It!

Object Oriented Programming isn’t a new concept here on the Developer Forum. People have been doing it for years. However I always found an issue with how people structure their “Classes” and “Objects”.
Here is what a template for my “Classes” look like.

--[[SERVICES]]--
--[[FOLDERS]]--
--[[MODULES]]--
--[[TYPES]]--
export type Fruit = {
	--Properties
	Age: number,
	Cost: string,
	Name: string,
	--Functions
	
}
--[[VARIABLES]]--
local FruitClass = {}
FruitClass.__index = FruitClass
--[[FUNCTION DECLARATIONS]]--
--[[FUNCTION DEFINITIONS]]--
FruitClass.Eat = function(self: Fruit) : ()
	
	print("This fruit has been eaten. It costed " , self.Cost)
	
end

FruitClass.Throwaway = function(self: Fruit) : ()
	
	print("This fruit has been thrown away. Its age was ", self.Age , " days")
	
end
--[[SCRIPT]]--
local Fruit = function(Name: string, Age: number, Cost: string) : Fruit
	
	local self = setmetatable({}, FruitClass)
	
	--Set Properties
	self.Age = Age
	self.Cost = Cost
	self.Name = Name
	
	return self
	
end

return Fruit

This way when I want to create an object, when I required the class, the only thing returned to me is the function or the “Constructor”. It looks like this when used in another script to create a “banana”

local Fruit = require(script.Fruit)
local Banana = Fruit("Banana", 5, "$2.50")

This solves one of the main issues with the common method of OOP, where the “New” function or constructor is accessible as a method within the object itself. My method appears to be more similar to other languages with official OOP implementation where you only have access to public values

Let me know what you guys think! Is this better or worse than the common way Roblox scripters create and use “Classes” in Luau. Would you be willing to use this format?

3 Likes

Been using this guy’s class module recently and I haven’t thought of metatables ever since:

I can see the attraction in the ease of use! But that model is just metatables abstracted to look simpler. In fact the “classes” and “objects” themselves are still metatables from what I can see.

And? It removes the hassle of working with metatables. I don’t need to think about them. Whether in the original style, I do.