Is this bad practice?

For example we have script to render gui slots for inventory:

local Render = {
	["Displayed"] = {}
}
local player = game:GetService("Players").LocalPlayer
local System = script.Parent.Parent

-- Services
local ReplicatedStorage = game:GetService("ReplicatedStorage")

-- Modules
local ItemData = require(ReplicatedStorage.ObjectsData.ItemsData)

-- Gui
local Inventory = player.PlayerGui:WaitForChild("Inventory").Main
local DisplayItems = Inventory:WaitForChild("SelectedSection").Inventory.Display.Items --/ sometimes it doesn't load soo use WaitForChild
local WeightBar = Inventory:WaitForChild("SelectedSection").Inventory.WeightIndicator.Bar

-- Create new frame and set it's parent to displayed items folder
function Render:CreateItemFrame(Item: ValueBase): GuiBase
	local NewFrame = System.Item:Clone()
	NewFrame.Name = Item.Name
	NewFrame.Image = ItemData[Item.Name].Image
	if Item.ClassName == "IntValue" then NewFrame.Count.Text = Item.Value end
	
	NewFrame.Parent = DisplayItems

	return NewFrame
end

-- Updates item count
function Render:UpdateItemCount(Frame: ImageLabel, Item: ValueBase)
	Frame.Count.Text = Item.Value
	if Item.Value <= 0 then Frame.Visible = false else Frame.Visible = true end
end
	
function Render:UpdateWeightBarSize(Weight: number, MaxWeight: number)
	local percent = Weight/MaxWeight
	WeightBar.Size = UDim2.new(percent,0,1,0)
end
return Render

As you can see this script have 3 methoods, 2 of them are updating different parts of Gui, one is updating Item Count Frame, and second weight bar which shows how heavy this inventory is, the question is that is this bad practice to have function to perform 1 hardcoded task?

2 Likes

Nope that’s perfectly fine if not a good practice. Segregating different code blocks into functions can make debugging easier in addition to having other benefits. As an example of the scalability functions provide, if you end up adding a mechanic that requires the item count to update somewhere else in your code you can just call the function you’ve created. Additionally a function can also provide you with the ability to easily test features without having to run code unrelated to the things you’re testing. It’s important to mention that functions aren’t always the key though. In cases where you know pieces of code likely won’t be reused elsewhere in your script or there is no gain in maintainability / readability it’s better to forego a function entirely.

TL;DR: Separating code into functions like this can allow for readability, scalability and maintainability.

3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.