#Code Organization to Prevent Circular Dependency (Two packages depend on structs from each other)

10 messages · Page 1 of 1 (latest)

sacred dragon
#

I have some code which consist of two packages, a api package and a student package (this is a hypothetical example to illustrate something I am having when reorganizing my current codebase) .

The student package contains logic to connect to a database, update student grades, fetch their grades, add students, remove students, and so on.

The api package implements an API and uses functions from the student package. So /addstudent in the api package may call AddStudent() in the student package.

In the api package I have a struct that represents a JSON request I expect to receive , and then that gets passed to the student package at one point.

// from api package 
type StudentCreationRequest struct {
  name string
  age int
}

But in the student package I also have a struct that represents a student , and that may get returned and used in the api package.

// From student package
type Student struct {
  name string
  age int
  grade int
  ... bunch of other stuff
}

Of course, this results in a circular depends and nothing will compile.

Is there a best practice to deal with packages importing structs from each other? Maybe making a dedicated package for the structs could work, but I don't know if that is best practice

lean zenith
#

one good practice is too not have too many tiny packages

#

alternatively though, yes you'd have to move shared stuff into package that both import. but consider just merging the 2 instead

sacred dragon
#

Hmm, I guess coming from more OO languages I may be thinking of packages as Classes, and that may be a flaw in some of my organization

Is there a rule of thumb when something should be in its own package

I do like the idea of separating stuff related to API, Database, and core functionality into its own compartments though

#

The other option I can think of is to have split the packages into api, database, and student

And then api would import database and student

But then a function like AddStudent would be implemented in api, and call functions in database and student

lean zenith
#

it's blocks and at the top it's glued together? it's a bit hard/vague/generic but the runtime may be like this

[ api (handlers?)  ]
[ DB   ][ biz logic]

but you would probably then define the data objects your using, and either get them directly out of db or transfer from db obj to biz obj... as often "it depends"

calm comet
#

The thing your calling should define the object it wants

#

And / or you define the thing you’re wanting to call as an interface