Object-Oriented Programming

Grouping Functions

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

Free Functions

A function that is not a member of a class

  • Useful for algorithms performed on the parameters
  • All IN data is from a value or const reference parameter
  • All OUT data is from a reference parameter or the return value
  • Does not save state between calls
  • Typically group (or organized) by file, e.g., xml_parser.hpp

Problem: Conflicting Names

  • Multiple free functions with the same name and parameter list
  • Causes a conflict
  • Means that pdf_parser.hpp and yaml_parser.hpp cannot be used in the same code
  • We should not restrict the potential environment for our code to be used in

Problem: Conflicting Names, Solution?

  • Has a prefix, pdf_ for the pdf parser, yaml_ for the yaml parser
  • Prefix would be used for all functions provided
  • Solves the conflict
  • More of a C-library form
  • Could also extend to class names, variables, and other program elements that we name
  • However, we have better options available
  • We should not restrict the potential environment for our code to be used in

Better Solution: Namespaces

  • A language feature to group functions and provide an organizing name
  • Can contain:
  • free functions
  • variables
  • classes
  • typedef

Cumulative Namespaces

  • All of the contents of a particular namespace do not have to be declared at the same time
  • They can even be declared in separate files

Namespace Aliases

  • The type optional exists in both std:: and boost::
  • The namespace opt can refer to either boost or std
  • Does abstract the choice but requires tracing back when needed
  • Useful in conversion or potential flexibility
  • Not a long-term solution due to the abstraction cost

Another Option: Static Methods of a Class

  • static class methods do not have access to data members/fields
  • They do have access to static data members/fields
  • We will consider that another time
  • For now, considering methods that could be free functions but, due to naming issues, are not
  • No advantage over namespaces, except that it may be joined with non-static member functions
  • We can easily put classes in a namespace
  • We can also nest classes ("inner classes"). However, in C++, this often causes more pain than it's worth. Every time I've done this, I ripped them out at some point.