Warm tip: This article is reproduced from serverfault.com, please click

Type aliases for documentation purposes

发布于 2020-11-28 14:40:00

Is it considered good practice to use type aliases to make go code more self documenting? An example:

type User struct {
    // user stuff
}

type Username = string

func Foo(users map[Username]User){
    // do stuff
}

It's pretty obvious that Foo takes a map from username to user struct without needing to explain anything in comments, which would probably be needed if the type definition was map[string]User Are there any negatives with this approach?

Function parameters are like local variables, but they also serve as documentation.

Where the types are descriptive, they should be short:

func AfterFunc(d Duration, f func()) *Timer

func Escape(w io.Writer, s []byte)

Where the types are more ambiguous, the names may provide documentation:

func Unix(sec, nsec int64) Time

func HasPrefix(s, prefix []byte) bool

Quoted from https://talks.golang.org/2014/names.slide#9. Making types less ambiguous seems like a worthy goal. time.Duration is simply type Duration int64, which is not an alias, but purely from the documentation perspective I think the effect is similar.

Questioner
user2133814
Viewed
0
Flimzy 2020-11-29 00:55:36

I hesitate to answer, because this is ultimately an opinionated question. But the reasons I would avoid this are:

  1. It's very non-obvious, and thus arguably violates the Principle of Least Astonishment. If I ran across that in some Go code, I would think it was a mistake, or cruft from a migration, and I would try to remove it.
  2. Even at face value, the documentation value is dubiuos, at best. It should be pretty clear from context that map[string]User should map usernames to users. If you have multiple similar maps, one which maps usernames, one which maps userids, for example, the name of the variable should disambiguate. If it doesn't, a type alias probably won't be sufficient either. You'll need some clear documentation.
  3. And finally, static analysis tools, such as those built into many IDEs, will resolve a type alias to it's canonical type, which means that any perceived documentation value will be limited anyway.