VS2008 Passing Variables - struct vs struct components - advantages/disadvantages?
I really hope this isn't one of those super basic questions.
Anyway, I've got a struct with 47 components, and I'm calling various functions that use anywhere from 3 to 10 of these components at once.
Is it better to call the function like:
foo(pParam->variable1, pParam->variable2, pParam->variable3)
or foo(pParam)
and then in the fun开发者_如何学Cction use pParam->variable1; pParam->variable2; pParam->variable3;
?
Thanks in advance!
You should pass the struct by reference, that way you don't need to copy all the values:
void foo(mySturct pParam); //Here the struct will be copy constructed.. relatively large overhead
void foo(Val1 param1, Val2 param2, Val3 param3); // 3 parameters passed by value, the value will be copied.
void foo(mySturct &pParam); //Only the reference to the structure is passed. Single pointer size value is passed.
In general structures are there so you can unite data. So it doesn't make sense to take it apart and pass different parameters to functions.
It should stay as a single unit.
I've been in a similar situation. Pass each component separately. That makes it clear to callers which values are required, and it makes it clear to implementors which values are available.
If you pass the whole struct, then callers will be unsure how much of the struct they really need to populate. Worse, the function implementers may start referring to another struct member that isn't always available, or isn't always valid.
Yet another thing you might see during maintenance is that certain unused struct members might be overloaded to pass new parameters that weren't anticipated before, and the field names will no longer match the values they represent.
Passing all the parameters separately makes it clear to everyone what the contract really is, and it makes the addition of new parameters explicit.
I think it is better to think more about the architecture. A struct with 47 attributes, passed to various functions which do not use all of them looks like Anemic Domain Model. You should split it up into classes, each class containing methods that only work with the data in the class. This way you avoid both passing the struct (you get it for free with classes) and problems with scaling your program.
精彩评论