Trying to clean up repetitive code using modules, good idea?

I’m trying to just clean up stuff that I use a lot in my UI, by putting certain actions into modules, for example I have a ‘Click’ and a ‘Hover’ module for when buttons are clicked or hovered over.

-- Click
return function(object, x, y)
	object:TweenSize(UDim2.new(x - 0.05, 0, y - 0.05, 0), Enum.EasingDirection.Out, Enum.EasingStyle.Linear, 0.1, true, function()
		object:TweenSize(UDim2.new(x, 0, y, 0), Enum.EasingDirection.Out, Enum.EasingStyle.Linear, 0.1, true)
	end)
end
-- Hover
local Hover = {}

function Hover:On(object, x, y)
	object:TweenSize(UDim2.new(x + 0.025, 0, y + 0.025, 0), Enum.EasingDirection.Out, Enum.EasingStyle.Linear, 0.1, true)
end

function Hover:Off(object, x, y)	
	object:TweenSize(UDim2.new(x, 0, y, 0), Enum.EasingDirection.Out, Enum.EasingStyle.Linear, 0.1, true)
end

return Hover

Just wanna know if this is a good idea? If theres a better way or if what I’ve done is good?

1 Like

Well it looks good to me, it’s already pretty short.

But, I think you should use Tween service instead. This is because you can predefine the TweenInfo instead of setting it every time.

[NOTE!: Only applies to the hover script]:

local TS = game:GetService("TweenService")
local TI = TweenInfo.new(The tween info)

local Hover = {}

function Hover:On(object, x, y)
	TS:Create(object, TI, {Size = UDim2.new(x + 0.025, 0, y + 0.025, 0)})
end

function Hover:On(object, x, y)
	TS:Create(object, TI, {Size = UDim2.new(x, 0, y, 0)})
end

return Hover
1 Like

If you’re not using self, use . instead of : to avoid passing the self argument implicitly since its not being used.

-- Hover
local Hover = {}

function Hover.On(object, x, y)
	object:TweenSize(UDim2.new(x + 0.025, 0, y + 0.025, 0), Enum.EasingDirection.Out, Enum.EasingStyle.Linear, 0.1, true)
end

function Hover.Off(object, x, y)	
	object:TweenSize(UDim2.new(x, 0, y, 0), Enum.EasingDirection.Out, Enum.EasingStyle.Linear, 0.1, true)
end

return Hover
1 Like