C++ antipattern
Mar. 31st, 2004 08:46 am![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
In C, and in C++ code written by people who still think they're writing C (and, in their defense, most of this code dates from before wide adoption of the STL and before ISO-standard C++ compilers were commonplace), a common pattern for functions which output strings (or other arrays) is to pass in an array and the length of the array as parameters to the function, and expect this array to be filled in by the function. For example:
int FameDate::GetDateAsString(char * output, unsigned int MaxStringLen)
So far, so good. The antipattern comes in when a default value is declared for MaxStringLen, especially one that is much larger than programmers might ordinarily expect. This leads to people doing:
char datestr[20];
myDate.GetDateAsString(datestr);
even though the default value for MaxStringLen might be 40 or more. The consequences are left as an exercise for the reader.
I'm trying to boil this antipattern down to a simple rule, and the best I've got is this: An array and its length are one logical object - it should never be possible to pass in only the array without its length. This has the advantage of pointing out that things like sprintf and strcpy are fundamentally prone to error, but we knew that. It has the disadvantage of being a rather clumsy statement.