TITLE: where to put small utility functions (Newsgroups: comp.lang.c++.moderated, 18 Aug 98) BASHAN: "Erez Bashan" > Not once in my classes I happen to need small local functions to do some > kind of simple service. Like in the old C days, this function serve only > to > save on code duplication, and have nothing to do with the class > abstraction > (no meaning in the model) or the class implementation (doesn't changes > the > class' state, or uses its members) other than simply being needed by the > other class methods. Which approach is better: > > 1. Implement it as a regular private method of the class. > 2. Implement it as a static private method of the class. > 3. Implement it as a function, in the implementation file of the class. > > I tend to prefer option 3 above, but somehow feel more comfortable to > put > the function "in the class". I could use the same namespace, if only my > compiler would support it ... KANZE: jkanze@otelo.ibmmail.com For simple cases, I'll also use 3. It has the disadvantage, however, that the function cannot access private members. Once the class becomes even a little complicated, I'll switch to the compiler firewall idiom; in such cases, of course, the added function becomes a member of the implementation class. TRIBBLE: David R Tribble (private email) Personally, I prefer a more "true" O-O approach, in that I believe that every function, variable, type, and constant should be a member of some class. (Some "true" O-O languages, like Java and Eiffel, enforce this.) I think nonmember variables and functions are a bad idea. Following this approach, then, a utility function should be written following rule #1 or #2 above. At the very least, you get the benefit of the parent class acting like a namespace, especially if your compiler doesn't yet support real namespaces. The class also serves to group the utility function with other related functions and types. The only grouping you get with nonmember functions is by using some kind of naming convention, and even then you're not guaranteed your names won't collide with someone else's. The only disadvantage is that you have to declare the (private) utility functions in the class header, but then this is an inherent problem with private members in C++ anyway.