Chapter 9. Functional OOP

Dealing with immutable variables brings up an interesting question as we dive into object-oriented programming (OOP): “Why would we have an object if we’re never going to change it?” This is where I’ve seen many people have an epiphany about functional programming. They understand the concept that an object is no longer something that “acts”; instead, it “contains” data.

As we go through this chapter, my hope is that you’ll also understand that objects are merely containers that encapsulate a set of data. We’ll answer the question “How does work get done?” by using static functions that will take our objects.

Back at XXY, your boss has asked you to extract the “send email” logic so that you can send emails for any type of report that might be requested in the future. He wants this to be done such that no other code that already calls sendEmail() has to be modified.

Static Encapsulation

Let’s begin by refactoring. Your boss wants you to extract the def sendEmail() function so that the functionality can be reused. Let’s first look at the Contact class and the corresponding def sendEmail() function that we will be migrating, as shown in Example 9-1.

Example 9-1. Send Email original
class Contact(val contact_id : Integer,
              val firstName : String,
              val lastName : String,
              val email : String,
              val enabled : Boolean) {

  def sendEmail() = {
        println("To: " + email + "\nSubject: My Subject\nBody: My Body")
  }

}

Let’s begin extracting this functionality by creating a function ...

Get Becoming Functional now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.