Any improvements to my module?

I’ve recently created a Binder module similar to the one they showed in the ROBLOX video about 5 powerful code design patterns because I can’t find anything like it online and I also wanted to create for personal use.

Any improvements that I could apply on my module?

local Binder = {}
Binder.__index = Binder

-- Services

local CollectionService = game:GetService("CollectionService")

-- Variables

local Trove = require(script.Trove)

-- Main

function Binder.new(tag: string, class)
	local self = setmetatable({
		_trove = Trove.new(),
		_tag = tag,
		_bounded = false,
		_classes = {},
		_class = class,
	}, Binder)
	
	self.BindAdded = CollectionService:GetInstanceAddedSignal(self._tag)
	self.BindRemoved = CollectionService:GetInstanceRemovedSignal(self._tag)
	
	function self:Bind()
		if not self._bounded then self._bounded = true end

		self._trove:Add(
			self.BindAdded:Connect(function(instance)
				self._classes[instance] = self._class.new(instance)
				print("Binded to " .. instance.Name)
			end)
		)

		self._trove:Add(
			self.BindRemoved:Connect(function(instance)
				self._classes[instance]:Destroy()
				self._classes[instance] = nil

				print("Unbinded " .. instance.Name)
			end)
		)

		for _, instance in pairs(CollectionService:GetTagged(self._tag)) do
			self._classes[instance] = self._class.new(instance)
		end
	end
	
	function self:Unbind()
		if self._bounded then
			print("Bind unbinded")
			self._trove:Clean()

			for instance, classObject in pairs(self._classes) do
				classObject:Destroy()
				self._classes[instance] = nil
				print("Bind destroyed and cleaned up")
			end
		else
			error("You can't unbind if you haven't bind anything yet")
		end
	end
	
	print("New bind created")
	
	return self
end

return Binder

One of the issues with this script is that the metatable and functions are created in the constructor. That means a lot of memory will be used up.

I recommend using the __index metamethod so that you only have to store the functions once in memory.

Any examples on how that would look like?

Like this:

Even if there’s multiple “Car” objects, they will still point to this function.

1 Like

You could always add a check to see if the argument given in Binder.new is an object and isn’t nil. You could also provide a better error message such as saying that the developer needs to call :Bind() before calling :Unbind().

2 Likes