News for hackers. Stuff that matters.
Re:Golang concepts from an OOP point of view by skybrian on Monday September 12, 2016 @07:07PM (#12484394)
I recently heard a rule of thumb: "accept interfaces, return structs".

I haven't put it into practice, but it seems like this should give callers enough flexibility to pass in whatever they like.

Re:Golang concepts from an OOP point of view by lloeki on Tuesday September 13, 2016 @02:28AM (#12486006)
Indeed I remember someone laying out some Go good practices (Rob Pike? Andrew Gerrand? damn can't recall) and "accept interfaces, return types" was definitely one of them. Again, a rule of thumb that works very well in most (not all) cases, and, conversely, a code smell.
Re:Golang concepts from an OOP point of view by zalmoxes on Monday September 12, 2016 @10:03PM (#12485148)
That really depends on what you're tying to do. Say you have a Datastore interface, which has some methods like "Create", "Update", "Delete", and a MySQL + an inmem implementation.

You can have `datastore.New() Datastore`, which returns one of the implementations, or you can have `datastore.NewMySQLStore, datastore.NewInMemStore()`. Now you need a different method for each implementation.

Also be careful with returning concrete type, you can run into this issue: https://play.golang.org/p/WHAW1X6elS

Re:Golang concepts from an OOP point of view by patates on Tuesday September 13, 2016 @07:29AM (#12487088)
Wow, that seems like a big issue. Is this accepted as a bug and being worked on or yet another feature?
Re:Golang concepts from an OOP point of view by weberc2 on Tuesday September 13, 2016 @11:31AM (#12489133)
It's not a bug. Interfaces are reference types. In this case, the interface is implemented by a pointer type. The interface can be thought of as a pointer to a nil pointer, but the "interface pointer" itself is not nil.

This is a tricky concept until you learn that interfaces are reference types.

Here's a simplified version of the previous example that illustrates this concept: https://play.golang.org/p/pODBgaHXq5

Re:Golang concepts from an OOP point of view by weberc2 on Tuesday September 13, 2016 @11:44AM (#12489298)
Hmm, I'm not sure that rule of thumb is very good. I think a better one would be "accept interfaces when you want polymorphism". Often I have a very high degree of confidence that your caller will never want to pass a different implementation, and creating the extra interface for an improbably hypothetical situation just isn't worth my time? I'm not making any statements here, just wondering out loud.