Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Static" method design

Tags:

go

I'm looking for advice on the best way to clean up the following structure. I know Go doesn't have static methods and it's usually better to encapsulate functionality in a separate package. My struct types reference each other, and so cannot be declared in separate packages because of circular imports.

type Payment struct {     User *User }  type User struct {     Payments *[]Payments }  func (u *User) Get(id int) *User {     // Returns the user with the given id  }  func (p *Payment) Get(id int) *Payment {     // Returns the payment with the given id  } 

But, if I want to load a user or payment, I'm just throwing away the receiver:

var u *User user := u.Get(585) 

I could namespace the functions themselves, which strikes me as unclean:

func GetUser(id int) *User {     // Returns the user with the given id  }  func GetPayment(id int) *Payment {     // Returns the payment with the given id  } 

I would really like to be able to just call .Get or similar on the struct without writing the name of the struct in the function itself. What's the idiomatic way to do this?

like image 887
atp Avatar asked Sep 07 '13 21:09

atp


2 Answers

GetUser() and GetPayment() strike me as perfectly clear and idiomatic. I'm not sure what you find unclean about them.

Calling .Get() on a struct to return another struct is the thing that strikes me as very odd, unclear, and unidiomatic.

I think this might be a case of just sticking with the idiom and trusting that you'll get used to it.

like image 133
Darshan Rivka Whittle Avatar answered Oct 10 '22 06:10

Darshan Rivka Whittle


Golang does not support constructors.

Use factory functions instead (Effective Go reference). The convention is to use New prefix:

func NewUser(id int) *User {     // Returns new User instance } 

The difference between constructor and factory function is that factory function is not "attached" to the User struct. It's a normal function that happen to return User while the Java/C++ like constructor is a method that modifies newly created User object in place.

like image 22
Grzegorz Luczywo Avatar answered Oct 10 '22 06:10

Grzegorz Luczywo