8 Elements of Object-Oriented Programming

 

In this chapter

  • Defining contracts using interfaces
  • Implementing a hierarchy of expressions
  • Implementing the adapter pattern
  • Extending behavior with mix-ins
  • Alternatives to pure OOP and a functional alternative to implement expressions

In this chapter we will cover the elements of object-oriented programming and see how we can employ them effectively. You are probably familiar with these concepts, as they show up in all object-oriented languages, so we’ll focus more on their use cases.

We’ll start with interfaces and see how we can think of them as contracts. After interfaces, we’ll look at inheritance: we can inherit both data and behavior. An alternative to inheritance is composition. We’ll look at some of the differences between the two approaches and when to use which. We’ll talk about extending data and behavior with mix-ins or, in TypeScript, intersection types. Not all languages support mix-ins. Finally, we’ll look at alternatives to OOP and when it might make sense not to use it. This is not because there is something wrong with OOP, but many developers learn it as the only approach to software engineering, and sometimes it ends up being overused.

Before getting started, let’s quickly define OOP.

8.1       Defining Contracts with Interfaces

8.1.1 Exercises

8.2       Inheriting Data and Behavior

8.2.1 The Is-A Rule of Thumb

8.2.2 Modeling a Hierarchy

8.2.3 Parameterizing Behavior of Expressions

8.2.4 Exercises

8.3       Composing Data and Behavior

8.3.1 The Has-A Rule of Thumb

8.3.2 Composite Classes

8.3.3 Implementing the Adapter Pattern

8.3.4 Exercises

8.4       Extending Data and Behavior

8.4.1 Extending Behavior with Composition

8.4.2 Extending Behavior with Mix-ins

8.4.3 Mix-in in TypeScript

8.4.4 Exercise

8.5       Alternatives to Purely Object-Oriented Code

8.5.1 Sum Types

8.5.2 Functional Programming

8.5.3 Generic Programming

8.6       Summary

8.7       Answers to Exercises

sitemap