You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Function-style options are used in constructors as follows
NewThing(namestring, opts...Option) *Thing
The are very commonly used (especially in IPFS libraries) but they have a number of negative traits:
how to handle duplicate options, which can occur when combining lists of options from multiple sources
how to handle options that have overlapping responsibilities, such as options that touch 2 or more aspects of the object
how to remove an option in a configuration chain, such as when overriding options read from a config file by an option derived from a flag
they are verbose to write since you need to prefix each one with the package name
they clutter the documentation with many extra functions
they are hard to find in documentation unless they are named with a standard pattern or grouped as constructors
it's difficult to inspect the default configuration or log configuration in use
Using a Config struct is simple and avoids the problems above. The constructor signature looks like:
NewThing(namestring, cfg*Config) *Thing
Passing nil is interpreted as using the default config. It's conventional to provide a DefaultConfig function that returns a non-nil Config with default values populated. Users can then override fields. It's also easy to inspect the code to determine the default config.
The Config pattern is used in some IPFS packages (go-log) and it's commonly used in the Go standard library (Conn.BeginTx, jpeg.Encode, crypto.Signer) whereas function-style options are never used.
A user of the package can create their own function-style options to build config if they wish.
The text was updated successfully, but these errors were encountered:
Function-style options are used in constructors as follows
The are very commonly used (especially in IPFS libraries) but they have a number of negative traits:
Using a
Config
struct is simple and avoids the problems above. The constructor signature looks like:Passing nil is interpreted as using the default config. It's conventional to provide a
DefaultConfig
function that returns a non-nilConfig
with default values populated. Users can then override fields. It's also easy to inspect the code to determine the default config.The Config pattern is used in some IPFS packages (go-log) and it's commonly used in the Go standard library (Conn.BeginTx, jpeg.Encode, crypto.Signer) whereas function-style options are never used.
A user of the package can create their own function-style options to build config if they wish.
The text was updated successfully, but these errors were encountered: