Skip to main content

Section C.19 J4: Using OO Properly, OO in C, The Expression Problem, Visitor Pattern

Synopsis.

This lecture shall consolidate the understanding of OO software (design) by giving different perspective. We do this in three parts.

  1. We introduce a small example (abstract syntax of a small expression language) and model the data structure in a functional, imperative, and OO language. Functional languages have algebraic data types and matching that make the life of the programmer easy. In C one needs to literally implement tagged unions and do the case distinctions on a very low level. In OO, each variant becomes a class and the name of the ADT is typically an interface. The cases of the functional and imperative programs become individual methods in the respective classes.

  2. We discuss how virtual method calls are actually implemented by looking at a corresponding implementation in C. The important thing here is to understand that the address of the vtab corresponds to the dynamic type of the object. Instead of doing a case distinction as in (1), we use a double indirection to directly (and efficiently) jump to the right code.

  3. The Expression Problem shows the difference of the case-distinction style and OO style when extending a class hierarchy. Adding new variants, can be locally done in OO but requires global changes in case-distinction languages. Adding new functionality can be done locally in case-distinction approaches but require global changes in OO. The visitor pattern can help here because it allows for “factoring out” the extension point. Here, understanding the interplay between overriding and overloading is intricate and crucial and can help to understand these two techniques in general.

Sections Covered.

Section 8.10, Section 8.11, Section 8.12