Parameter groups #8020
Replies: 2 comments
-
Beta Was this translation helpful? Give feedback.
-
I first encountered this pattern back when I was primarily writing Delphi code, and I think the answer I learned then is still applicable today.
If you have a common set of parameters that always (or almost always) show up together, then your code is telling you there's a domain object you need to define. For example, if you have this code: public static class Example
{
public static void MethodA(int a, int b, int c) => Console.WriteLine(a + b + c);
public static void MethodB(int a, int b, int c) {MethodA(a, b, c); ...}
public static void MethodC(int a, int b, int c) {MethodB(a, b, c); ...}
} Consider what the three ints actually mean. Maybe they're a public static class Example
{
public static void MethodA(Vector v) => Console.WriteLine(v.X + v.Y + v.Z);
public static void MethodB(Vector v) {MethodA(v); ...}
public static void MethodC(Vector v) {MethodB(v); ...}
} or maybe they're a set of metrics public static class Example
{
public static void MethodA(Metrics m) => Console.WriteLine(v.a+ v.b + v.c);
public static void MethodB(Metrics m) {MethodA(m); ...}
public static void MethodC(Metrics m) {MethodB(m); ...}
} Having parameter groups might solve the immediate issue of passing identically named parameters around (*), but it doesn't do anything about addressing the underlying problem with the cod.e (*) By definition, this would make renaming a parameter into a breaking change, one that silently changed the behaviour of other code. This feels like a good way to create code that other developers are to afraid to touch. Is that a good idea? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I often have methods passing their parameters unmodified to other methods with similar signatures, like so:
This adds rigidness that can be difficult to refactor later. Say I change the signature of MethodA. Now MethodB and MethodC need to also be updated accordingly. There is also that it tends to get tedious to write and look at. Currently you can work around this via passing in classes and structs, but this solution comes at the inconvenience of the caller.
It would be better to have common parameters for methods defined in such a way that they wouldn't need to be individually repeated in method signatures, and the caller wouldn't need to do ugly instantiation nesting in their calls. I propose the ability to define parameter groups, which can be placed in method signatures and calls via the spread operator.
With this kind of feature, methods wouldn't need to define the same group of parameters every time, and callers wouldn't need to nest class/struct instantiations in their calls.
Beta Was this translation helpful? Give feedback.
All reactions