go-structure-examples icon indicating copy to clipboard operation
go-structure-examples copied to clipboard

Question about Service interface in service packages

Open soqt opened this issue 6 years ago • 4 comments

Hi Kat, after watching your talk, I found your project structure is very inspiring and I'm migrating my project to this structure now. I have a question. Why do you want to create a Service interface in every service package instead a Service struct? and all functions with (s *Service) automatically bind to the struct. Is there any special use case for Service interface?

soqt avatar Sep 28 '19 09:09 soqt

With a Service interface for each service you can create mocks to make testing easier wherever they are used(eg. handlers). You also get the benefit of being able to wrap your services with logging, tracing, metrics middleware.

godwhoa avatar Sep 28 '19 09:09 godwhoa

With a Service interface for each service you can create mocks to make testing easier wherever they are used(eg. handlers). You also get the benefit of being able to wrap your services with logging, tracing, metrics middleware.

Thanks for your answer. That makes much sense!

soqt avatar Sep 28 '19 09:09 soqt

Related to this: shouldn't the service constructors return the struct?

lewislbr avatar Feb 22 '21 08:02 lewislbr

I guess it's due to service struct not being exported. But yeah "accept interfaces, return structs" is a common saying.

godwhoa avatar Feb 22 '21 08:02 godwhoa