Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Option.Check() for Options struct input #9

Open
Pungyeon opened this issue Jun 24, 2019 · 0 comments
Open

Use Option.Check() for Options struct input #9

Pungyeon opened this issue Jun 24, 2019 · 0 comments
Labels
consideration enhancement New feature or request

Comments

@Pungyeon
Copy link
Owner

Based on the following reddit post from /u/kromem

A tip about using "options" parameters for stuffing function arguments, especially if using for non-optional arguments.

I suggest never passing in the options struct directly. There is no issue in the code with nil parameters that may actually be required as you refactor your code (i.e. if you add caching to your program, you might need a reference to the cache interface, and it'll be a pain to check EVERY function call to see if you included the caching interface once the API changed, especially if the variables are broken out into multiple lines).

Instead, if you want to go down this route, have every Options object have a "Check" method that verifies options are correct and returns a reference to itself, panicking if options are not correct (the point is to catch these issues in tests & not production, so not having to check an error on the method is cleaner).

This way you can pass in Options.Check() and your unit tests will panic where calls are out of date.

Otherwise, you are taking on significant technical debt using the options pattern for any non-optional parameters.

In general, I think this is a bit of an antipattern in a statically typed language with modern code editors, as identifying what a variable in a function call is can be as simple as moving the cursor onto it and seeing the type signature for all the parameters. Whereas including in-line defined structs sometimes breaks the editor type declarations. I think the ideal is to use the pattern only for optional parameters, but if mixing required and optional, a trick like the above will be a lifesaver.

Of course, make sure you have unit tests in place for any function that within it passes a checked option struct, or you will end up with panics in production.

@Pungyeon Pungyeon added enhancement New feature or request consideration labels Jun 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
consideration enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant