Why is this approach better? (FP and OOP)

For the last week or two I’ve been packing a few boxes every night as I prepare for a move a few miles to the north. Last night I started packing the old Beginning Scala book, when I noticed a bookmark I had in it. When I flipped to the bookmark, I found code like this:

trait Shape
case class Circle(radius: Double) extends Shape
case class Square(length: Double) extends Shape
case class Rectangle(h: Double, w: Double) extends Shape

which was later followed by code like this:

def area(s: Shape) = s match {
    case Circle(r) => r * r * Math.PI
    case Square(l) => l * l
    case Rectangle(h, w) => h * w

and code like this:

def perimeter(s: Shape) = s match {
    case Circle(r) => 2 * Math.PI * r
    case Square(l) => 4 * l
    case Rectangle(h, w) => 2 * h  + 2 * w

Both of those methods are defined in an object named Shape (or maybe Shapes, I’m doing this from memory now). The result is that those are like static methods in Java. The behaviors don’t belong to the individual Circle, Square, and Rectangle classes; instead, they are static methods that accept the base type of Shape.

Why is FP better than OOP?

I’m pretty sure Beginning Scala was the second Scala book I ever owned, after the classic, Programming in Scala, by Odersky and Spoon, and I remember why I put a bookmark on this page: When I first came across this code, I thought, “Why is this better than an OOP approach?

I’ll write more about this in future posts, but for today I’ll just leave this out here as a little bit of a quiz and ask, “Why do you think this approach might be better?” As part of your consideration, I think you need to ask yourself questions like these:

  • “How do the two approaches look when I use them?”
  • “What happens when I need to add more shapes, such as a triangle?”

Note: If you know about functional programming and algebraic data types, it might be interesting to know that the author of Beginning Scala, David Pollak, doesn’t really mention those in his book. I’m pretty sure he was aware of them, but I suspect that he didn’t want readers to get bogged down in definitions.

Yours in functional programming,