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.
I hesitate to answer, because this is ultimately an opinionated question. But the reasons I would avoid this are:
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.
would you say the same for a regular def
type Username string
?@mh-cbon: Not all of the points apply to a stabdard type definition. Which one are you asking about? Generally, though, I prefer to reserve type definitions for functionality, not documentation. I find constantly type converting back and forth between a named type and a base type to be cumbersome, and prefer to avoid it except when I have functionality built into a type.
I find constantly type converting back and forth between a named type and a base type to be cumbersome, and prefer to avoid it except when I have functionality built into a type.
this is a good reason i agree with. I raised the point in case OP is confused about the various type definitions.the concern about converting between a named type and base type isn't applicable to type aliases because type aliases don't actually create a type, so plain string's would work in my example, correct? this was actually one benefit I perceived from using type aliases.
@user2133814: Right, conversion is NOT applicable to aliases.