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.
classContact(valcontact_id:Integer,valfirstName:String,vallastName:String,val:String,valenabled:Boolean){defsendEmail()={println("To: "++"\nSubject: My Subject\nBody: My Body")}}
Let’s begin extracting this functionality by creating a function ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access