Quantcast
Viewing all articles
Browse latest Browse all 4

Answer by Gaurav Dhiman for How to write idiomatic constructor

In most cases constructor functions return concrete types (or pointer to a type).The situations in which returning interfaces might be a good idea is when calling factory functions or builder functions in which underlying concrete type satisfies that interface.

Consider error interface for example, when you call http.NewRequest underlying concentrate error type can be of net.Error, net.DNSError etc. Now try to think how are you going to create an api like this without an error interface if function returns concrete type? Only solution to it I can think of is to create a massive error type for net package and add fields for extra information, but its most probably much harder to maintain, test that kind of error type and not to mention memory bloat.

Whether you choose to return concrete type or an interface is a design choice, some guidelines exists to give solution to common scenarios.


Viewing all articles
Browse latest Browse all 4

Trending Articles