Trying to find the best practice in handling a connection using oop. does anyone have suggestions?

using oop and wondering if anyone has any suggestions for this bit a code. this is sample code i created to see if it’s something i may use for this npc class i’m making. for context, the connection may change from closest player. am just thinking if this is a good way to manage the connection… inside the module or should it be managed outside the module.

function person:setConnection(handle)
    if connections[self].connection then
        connections[self].connection:Disconnect()
    end
    
    connections[self].connection = self.model.MoveDirection.Changed:Connect(newValue) -- or proerty changed signal whichever.
        -- perform handle
    end)
end
3 Likes

spoke with someone about this and i think it’s better to handle the connection outside of the direct class

1 Like

If it’s feasible, I’d personally have your connections associated with your object, inside of your object.

One of the main benefits of object oriented programming is the factor of organization. Objects generally will be be independent of one another and we don’t need to worry about lingering references when the object is no longer needed, and can actually help prevent and/or resolve issues like memory leaks when you dispose of an object using a deconstructor, since everything you need to dispose of is right there. You can manually handle connections (like make each connection have a unique identifier as an index inside of the object) but there are also modules that can help manage connections like the maid by Quenty, each object has its own maid(s) and the maid can be destroyed when you go to destroy your object. In the maid’s deconstructor, you’d disconnect relevant events.

That isn’t to say you can’t have a utility method to handle connections for you, in fact I would say that’s a pretty good idea and if you need to know what connection does what, I’d actually say I would recommend doing that.

Anyway, back to my original point, the only thing is that I wouldn’t store each object as an index in a large collection of objects. It’s a pretty minute change but instead of doing connections[self].connection, I’d do self.connections.connection. self.connections would be a table of connections.

Then, again, when you go to destroy your object, just iterate through self.connections and disconnect the events inside of that table.

2 Likes

thanks this was helpful

tdgdsfgsdfg

1 Like