Circular Dependency of Modules

Hi, I was wondering if I could get some help structuring my module scripts so that any circular dependencies are removed. Currently I’m working on a system which lets you purchase a pickaxe and mine blocks with the pickaxe without exceeding the storage limit.

To achieve this I have a static ItemHandler class which stores a copy of each item in the game - including Pickaxes and Bags - and stores information on what’s currently equipped. Different Bags have different holding limits for blocks.

A Pickaxe uses the BlocksHandler static class to reward the player with blocks whenever a block is mined. In doing so, the BlocksHandler checks the limit of the number of blocks that the player can hold, which is dependent on the Bag that the player has equipped. The BlockHandler therefore needs to require the ItemHandler class to check what’s equipped.

This obviously leads to a circular dependency and so needs to be restructured a bit. Using the official roblox lua style guide, it’s recommended that any requires are at the beginning of the module, and so I shouldn’t be (for example) requiring the ItemHandler only in my :giveBlocks() method when it’s already instantiated. Does anybody have any suggestions on how I can restructure my modules?

Thanks.

What is the responsibility of your BlockHandler class? Does it make sense to make it responsible for checking bag space? (This sounds like a responsibility of the ItemHandler, or the Pickaxe.)
The easy way to resolve this would be to give the BlockHandler information about bag space when you invoke it for blocks. It also makes more architectural sense and reduces coupling because the BlockHandler doesn’t really need the entire ItemHandler class.

Usually to handle circular dependencies you would give each module that depends on eachother an initiating function and you would have a master module fire that function with the arguments being the required other modules. So that way they all of have references of each other without having to require each other.

Rather than the ItemHandler manually searching for items, have the ItemHandler be an ItemRegistry where each item can register its existence and other items can use the registry to find other items. Minecraft does this. Many games do this.

Sorry, I should’ve explained better. The BlockHandler (Actually the SpendablesHandler, but I simplified its function a bit for the sake of this thread) stores information on the number of blocks being held by the user and contains methods for spending and receiving more blocks.

I thought about this, it’s just with the ItemHandler and BlockHandler I felt these should be static classes with no initiating function.

Thank you very much, I’ll go and give this a go now! This should work.

Thank you everybody else for your suggestions too!