Object-Oriented Programming

Function Generalization

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

Function Generalization

  • The term generalization is overloaded
  • For now, referring to making functions applicable to more situations
  • Very related to concerns

Notice

The following examples are, in many cases, not good design examples

To see which ones are which, you must listen to the presentation

Extremely Limited Sort ☚ī¸

Good Sort Interface 🙂

Good Sort Interface Scenario: Sort entire container 😊

Good Sort Interface Scenario: Sort subrange of elements 🙁

Better Sort Interface 😊

Better Sort Interface Scenario: Sort entire container and subrange 😊

Better Sort Interface Scenario: Sort subrange of elements in descending order ☚ī¸

Solutions for Descending Sort: Use flag ☚ī¸

Solutions for Descending Sort: Better Idea 🙂

Best Solution to Descending Sort 😊

C++ Template Version

Extremely Limited Binary Search ☚ī¸

Better Binary Search 🙂

Generalizing a Function

  • Change from assuming using all of a container, e.g., std::vector<int>& v, to iterators
  • Change a literal value (which is an assumption) into a parameter

Better Sort Interface 😊 (Revisited)

Better Sort Interface Scenario

  • Sort only the responses in the even positions
  • Call this a stride of 2
  • The C++ Standard Library does not provide stride versions

Sort with Stride 😇

Stride vs. No Stride 😊

Reuse 😇

Questions to Ask

  • Are we assuming a constant/literal that could change?
  • Are we assuming it is applied to the entire data set?

Even More Assumptions

  • Assumption: Container is std::vector
  • Assumption: Container elements are int
  • Assumption: Sorting in ascending order, i.e., smallest to largest
  • Solution: Generalize types using templates
  • Solution: Generalize comparison using templates

Viewpoint of Concerns

  • Why should the search() care about a fixed value? Only cares about the value type int
  • Why should the sort() assume we want to sort the entire container?
  • Why should the sort() assume we want a stride of 1?