If the function has too many arguments or arguments are growing or the they change often, what is the appropriate way to deal with it?
Long Parameter List
This approach is used when the caller needs to consider all parameters carefully.
If there are too many positional arguments, the same type can be hard to track, you can create named type for type-safe, for example:
1 | type UserID int64 |
Wrapped in Struct
Pros:
- Backward compatibility, the addition or removal of any field doesn’t alter the signature of the constructor.
- If the same set of parameters are passing around to lots of functions.
- Easier in unittest and mock.
- Can use method chaining to initialize parameters.
1 | type Request struct { |
Cons:
- The parameters are easy to slip without paying attention, need to handle the zero values or using zero value validators.
Functional Options Pattern
Refer: https://golang.cafe/blog/golang-functional-options-pattern.html
A pattern of structuring your structs in Go by designing a very expressive and flexible set of APIs that will help with the configuration and initialisation of your struct.
1 | package server |
Use it in client:
1 | package main |