Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalence of static methods in Go

Let's say in Java, I have class CryptoFormat, which has a static method named getLegacyFormat(). When I want to use the method, I just need to call CryptoFormat.getLegacyFormat(). This is clear because I know where the method comes from.

In Go, there is no static method. I don't really want to just make a file called crypto_format.go and define the method there. The reason is that whenever I need the method, I just call GetLegacyFormat(), which doesn't contain the context where the method comes from.

I could think of two ways to solve the problem:

  1. Make a separate package named cryptoformat, and define the method as a global function in the package. This way, I need to make a new package for just few methods. Also, whenever I need static methods like this, I have to define new packages.
  2. Define a struct named cryptoFormat containing method GetLegacyFormat(). Also, define a global public variable named CryptoFormat, which points to an instance of struct cryptoFormat. This way, I can call CryptoFormat.GetLegacyFormat() when I need the method.

I am not sure which one is better, or whether there is better way.

like image 284
Thanh Bui Avatar asked Jul 09 '17 00:07

Thanh Bui


2 Answers

I would say option 1 you mention is the more idiomatic way to define such functions, if they don't need any state that would warrant to tie them to an underlying struct.

If there is some state you'd like to have as context for the function, then option 2 would be the way to go.

Note that in Go, functions are "first class citizens", so you don't have Java's constraints of needing to define a class for static methods.

And yes, if you want a separate namespace you'd need to define separate packages (just as in Java you'd need to define separate classes and/or packages).

If you want your implementation to be idiomatic, I'd suggest you take a look at Go's standard libraries (pick a few packages and explore how they implement their functions) to get a better feeling of the usual ways to structure this.

like image 70
eugenioy Avatar answered Oct 20 '22 07:10

eugenioy


whenever I need the method, I just call GetLegacyFormat(), which doesn't contain the context where the method comes from.

So add context to the function name.

GetLegacyCryptoFormat()
like image 24
AJcodez Avatar answered Oct 20 '22 07:10

AJcodez