How to avoid circular dependencies but keep a clean structure

Viewed 566

I have this structure:

httpservice
L endpointHandler.go (it has as parameters databaseA and databaseB)
L types.gen.go (autogenerated from the api definition)

storage
L databaseA.go (each database has 'Store(Type)' and 'Get() -> Type' functions)
L databaseB.go

My problem is that I get into circular dependencies errors. The endpointHandler needs to import the storage package to access the databases. The databases need to import the httpservice because the types are autogenerated there (it needs the types in order to store or read the struct).

Is there a way to solve this issue with interfaces? I tried it but it didn't get rid of the circular problems. Some solutions I could think of:

  1. Copy paste the types in the storage package and ignore the generated types

  2. Move the databases inside the httpservice package, and forget about the nice folder structure

PD: There are a lot of questions about circular dependencies but I don't manage to solve my particular problem. Sorry if it's repeated.

1 Answers

If the application grows - you can consider using "ports and adapters" architecture concept to inverse the dependency.

In this case you don't want the depencency from "httpservice" to the low level "storage" package. (The httpservice probably acting as an interface to the outside should not know the technical details of the storage.. In fact the storage might be something different in future anyway). So you can define an interface in the "httpservice" layer (package) that has a meaning to that layer (e.g. "mydataService interface {}") - this i called a secondary port.

The "storage" layer can know the "httpservice" and implements an adapter (implementing the defined interface)

When initializing your application make sure you inject the correct storage adapter to the httpservice..

Some bigger frameworks also use this approach - you may want to read more: https://docs.flamingo.me/2.%20Flamingo%20Core/1.%20Flamingo%20Basics/4.%20Ports%20and%20Adapters.html

Related