Anybody think there are advantages to using a class or struct to pass arguments ?
Like instead of
f(int,float,string)
Have
f(Args)
Where Args
is struct
with int
,float
,string
members.
Advantage is easy to create multiple default parameters and not have to change function signature when new arguments added.
The obvious benefit would be to have logical grouping of semantically related data items.
Once you do, add some (member) operations on the structure that will guarantee your invariants.
The encapsulation raises the abstraction level of your code and this makes it easier to maintain/reason about.
See also Law Of Demeter
I think the great advantage is not having to rely to parameter order. Rely on order is error prone if you are changing frequently the interface, instead if you change the parameter struct you are always explicitly assigning values to a member variable which has a specific semantic.
Take for example Direct3D11 ID3D11Device::CreateDepthStencilState function: passing a const D3D11_DEPTH_STENCIL_DESC *pDepthStencilDesc
is a lot more clear than asking for all the parameter it require.
Moreover think about modifiability: you don't need to change this method signature but only the underlying data structure during refactoring. I've found this especially useful when working collaboratively, where someone specify the interface and someone else have to implement it.
Anybody think there are advantages to using a class or struct to pass arguments ?
Yes, I think there's a lot of advantages.
Having large parameter lists on functions will distract client code from semantical parameter consistency, which can be better managed within an appropriate struct
or class
.
Also it's more flexible to use a struct
, if additional (possibly optional) parameters need to be added later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With