Could my module loader be better?

Hey!

I was wondering if I could optimize or use better practices in my module loader. Any suggestions/help is appreciated.

local Library = {}

local Services = script:FindFirstChild("Services")
local Utilities = script:FindFirstChild("Utilities")

local LoadedServices = {}

-- Ensures that the modules were not already loaded (required recursively).

local function InitializedService(Name: string): boolean
	local Service = LoadedServices[Name]
	
	return Service ~= nil 
end

-- Ensures that the modules are valid (no inconsistencies).

local function EnsureValid(Module: ModuleScript): boolean
	local Passed = false
	
	assert(Module ~= nil, 
		("Module: '%s' is not a valid service."):format(Module.Name)
	)

	assert(Module:IsA("ModuleScript"),
		("Module: '%s' is not a module script."):format(type(Module))
	)

	assert(#Module.Name > 0,
		("Module: '%s' has an empty name."):format(Module.Name)
	)
	
	Passed = true
	
	return Passed
end

-- For returning services.

function Library.GetService(Name: string): ModuleScript
	assert(not InitializedService(Name), 
		("Module: '%s' has already been loaded."):format(Name)
	)
	
	local Service = Services:FindFirstChild(Name)
	
	if EnsureValid(Service) then 
		table.insert(LoadedServices, require(Service))
		debug.setmemorycategory(Service)
	end
	
	return Service
end

-- For returning utilities (e.g. Maid)

function Library.GetUtility(Name: string): ModuleScript
	local Utility = Utilities:FindFirstChild(Name)
	
	if EnsureValid(Utility) then 
		require(Utility)
	end
	
	return Utility.new()
end

-- For creating new instances in other scripts.

function Library.Insert(Class: string, Properties: any): Instance
	local Object = Instance.new(Class)
	
	for Key, Value in pairs(Properties) do
		if Key ~= "Parent" then
			Object[Key] = Value
		end
	end
	
	Object.Parent = Properties.Parent or workspace
	
	return Object
end

return Library
1 Like

I would wrap your require in a pcall.

Also assert throws an error if it fails, so for example EnsureValid() will never return false, it will only return true or throw an error.

Other than that I don’t see anything weird…

1 Like