Guidelines for complex arguments #187
Replies: 9 comments
-
How do you construct the |
Beta Was this translation helpful? Give feedback.
-
Not sure what you mean? I'm arguing that this: Foo::new(Options {
this: 800,
that: true,
other: 0.83,
also: 20,
btw: "do you even",
}) is probably better than Foo::new(800, true, 0.83, 20, "do you even") especially when many of the arguments have the same type: Foo::new(true, true, false, true) And I think it'd be handy for the guidelines to give, well, guidelines, about how to deal with complex constructors like that. |
Beta Was this translation helpful? Give feedback.
-
I'm not sure exactly why, but I've seen people/advice (maybe even in these guidelines?) shying away from making struct fields public and allowing their construction like that. Btw, there's a draft RFC that would help resolve this, IMO: Centril/rfcs#19 |
Beta Was this translation helpful? Give feedback.
-
I'm not sure exactly how that rfc helps? This is specifically for when the arguments are all required (i.e., there is no default). |
Beta Was this translation helpful? Give feedback.
-
The idea is you'd set the default value for the non-required fields and would only define the fields you want to define when constructing the value. |
Beta Was this translation helpful? Give feedback.
-
Right, but that doesn't help when you have many required arguments :) |
Beta Was this translation helpful? Give feedback.
-
Why not? (I'm sorry for making your issue here into a conversation with me 🙁) IIUC it would make your example the following: Foo {
this: 800,
that: true,
other: 0.83,
also: 20,
btw: "do you even",
optional_field: "I override your default value",
launch_missiles: true,
} |
Beta Was this translation helpful? Give feedback.
-
Ohhhhhh, I see what you're saying. I'm thinking more generally of the idea of constructors. The very specific case of "all you want to do is set the initial field values" I agree that defaults solve. I'm more worried about when you have methods (they don't even have to be constructors) that take many arguments. Perhaps the use of |
Beta Was this translation helpful? Give feedback.
-
Ah right! In that case it makes me think of @softprops' https://medium.com/@softprops/default-values-copy-that-ae43831781f3 |
Beta Was this translation helpful? Give feedback.
-
Builder are handy when you have a constructor many optional arguments (or arguments with defaults). However, in some cases you may have a constructor or method with many required arguments. In those cases, we should probably recommend passing some kind of
Options
struct
as an argument to the method with all the required parameters contained within it.Beta Was this translation helpful? Give feedback.
All reactions