OOP, is it still useful if there is only one object?

Hey! I learned OOP like a month ago but it feels like I’m almost never using it.
Some people told me it allows many people to write better code and stuff but for example, if I wanted to make a punch-system, how would I make it OOP?

Something like this, right?

local Punch = {}
Punch.__index = Punch

function Punch.Create()
	local newPunch = {}
	newPunch.Animation = ""
	setmetatable(newPunch, Punch)
	return newPunch 
end

function Punch:Punch(humanoid)
	local animationTrack = humanoid:LoadAnimation(self.Animation)
	animationTrack:Play()
	...
end

local newPunch = Punch.Create()
...
newPunch:Punch()

But would that even make any sense? I don’t think that’s really good OOP practice.

  • Yes, that would make sense
  • No, that wouldn’t make sense
  • Something else (comments)

0 voters

Am I doing something wrong?
Thank you!

1 Like

object oriented programming’s purpose is to make easily readable and organized codes by simplifying and grouping certain aspects as properties to allow for ease of adding new mechanics and adjustments, your use case is rather redundant as it’s effectively procedure programming. instead of making a new metatable solely for the punch, make a combat handler metatable that handles the punching, this way when you want to add in say a kick, you’d easily be able to do so instead of making another metatable for kick ultimately achieving nothing

local combatHandler = {}
combatHandler.__index = combatHandler

function combatHandler.Create(plr)
	local newHandler = {}
	newHandler.Humanoid = plr.Character:WaitForChild("Humanoid")

	newHandler.Punch = {}
	newHandler.Punch.Animation = ""

	setmetatable(newHandler, combatHandler)

	return newHandler 
end

function combatHandler:FirePunch()
	local animationTrack = self.Humanoid:LoadAnimation(self.Punch.Animation)
	animationTrack:Play()
end

local handler = combatHandler.Create(game.Players.LocalPlayer)
handler:FirePunch()
2 Likes

OOP is for different reasons such as to avoid having multiple functions for same reason here is a example:

Normal code

if (something == "something") then
print(something) --More code but this is an example
elseif (something == "otherthing") then
print(something)  --More code but this is an example
end

OOP code:

function(something)
print(something)  --More code but this is an example
end

Now thats not the best example but it’s just an example of what’s for OOP and what is not

@RoyalTHEUSERNAME has explained it better!

1 Like