iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔄

The Position of the Subject: Differences in Function Application Style between OOP and FP

に公開

Introduction: The Sensation of "Performing calc on shape"

When writing code, we unconsciously place a "subject."

// OOP style
shape.area()      // "shape" performs area (or returns area)

// FP style
area(shape)       // "area function" processes shape

Even though both perform the same calculation, the way they are read differs. The former is "performing area on shape," while the latter is "area uses shape."

This difference is not merely a matter of syntactic preference, but reflects a paradigm shift in how we perceive the relationship between data and operations.

Receivers and Arguments: The Location of Knowledge

In OOP, data (objects) "possess" behavior.

class Circle {
  constructor(private radius: number) {}
  area(): number {
    return Math.PI * this.radius ** 2
  }
}

const circle = new Circle(5)
circle.area()  // circle knows its own area

In functional programming, functions "know" the data.

type Circle = { radius: number }

const area = (c: Circle): number => Math.PI * c.radius ** 2

area(circle)  // area function knows the structure of Circle
Perspective OOP FP
Location of knowledge Data has behavior Function knows data
Direction of extension Easy to add new types of data Easy to add new operations
Unit of cohesion Class (data + operation) Module (type + set of functions)

This is also the essence of the Expression Problem.

Expression Problem: The Dilemma of Extension

The difference in the "direction of extension" shown in the table above corresponds to a classic problem known as the Expression Problem.

The Essence of the Problem

To the question, "Can both data types and operations be extended without modifying existing code?", OOP and FP provide different answers.

// OOP: Adding new data types is easy
class Triangle extends Shape {
  area(): number { ... }  // Add Triangle without changing existing code
}

// However, adding new operations is difficult
// → Need to add perimeter() to all classes
// FP: Adding new operations is easy
const perimeter = (s: Shape): number => ...  // Just add a new function

// However, adding new data types is difficult
// → Need to add a Triangle case to all functions

Which to Choose?

This is not a question of "which is superior," but a design decision based on predicting the direction of domain changes.

Expected Change Suitable Style
Increase in new types of data OOP (add classes)
Increase in new operations/processing FP (add functions)
Both increase equally Compromises like Visitor or extension functions

If the number of "product types" increases in an e-commerce site, designing in an OOP style makes changes easier; if "analysis/reporting functions" increase, an FP design is better.

Pipe Operator: Writing Data-Oriented Code in FP

Many functional languages enable data-oriented descriptions via the pipe operator.

# Elixir
shape |> area() |> format()
// F#
shape |> area |> format
-- Haskell (Data.Function & operator)
shape & area & format

These can be read almost identically to shape.area().format(). "Perform area on shape, then perform format on the result."

Reference: Haskell Style

Notation Direction Use Case
format (area shape) Inward → Outward Naive application
format $ area $ shape Right → Left Omit parentheses
shape & area & format Left → Right Data flow
format . area Right → Left Function composition

In the Haskell community, . and $ are mainstream, as there is a stronger culture of "assembling functions" rather than "flowing data."

Kotlin: An Intermediate Solution Using Extension Functions

While Kotlin does not have a pipe operator, it incorporates the strengths of both styles through extension functions.

// Extension function: Defined outside the class, but can be called with method syntax
fun Shape.area(): Double = when (this) {
    is Circle -> PI * radius * radius
    is Rectangle -> width * height
}

shape.area()  // OOP-like syntax

Furthermore, pipe-like descriptions are possible using scope functions:

shape
    .let { calculateArea(it) }
    .let { formatResult(it) }

Features of extension functions:

  • Syntax is shape.area() (OOP-like, has a receiver)
  • Definition is outside the class (FP-like, operations can be added later)
  • Maintains the receiver syntax while making the "operation addition" side of the Expression Problem easier.

TypeScript: Choosing Between Both Styles

TypeScript does not have a pipe operator (it is currently a Stage 2 proposal at TC39), but similar things can be achieved with libraries.

Managing Types and Functions in the Same File

// domain/shape.ts
type Shape =
  | { type: "circle"; radius: number }
  | { type: "rectangle"; width: number; height: number }

const area = (s: Shape): number =>
  s.type === "circle"
    ? Math.PI * s.radius ** 2
    : s.width * s.height

const format = (n: number): string => `${n.toFixed(2)}㎡`

export { Shape, area, format }

This essentially realizes cohesion where module = type + set of operations. You can create the same structure as an OOP class by combining discriminated unions and functions.

Data-Oriented (Left to Right)

import { pipe } from "fp-ts/function"

pipe(shape, area, format)
// shape → area → format
// "Perform area on shape, then format it"

Function Composition (Right to Left Definition, Applied Later)

import { flow } from "fp-ts/function"

const formatArea = flow(area, format)
// A new function that composes area → format
formatArea(shape)

Naive Nesting

format(area(shape))
// Data flows from the inside out
Style Syntax Suitable Scene
pipe(shape, area, format) Data flows One-time transformation
flow(area, format) Assemble functions Reusable transformations
format(area(shape)) Mathematical Simple composition

Starting Point of Thought: Data or Operation?

Whether "performing area on a shape" feels more natural, or "an area function processes a shape" feels more natural, depends on the starting point of your thinking.

Data-Oriented Thinking

  • "What can I do to this data?"
  • Typing shape. in an IDE shows a list of operations
  • OOP-like, Kotlin extension functions, TypeScript pipe

Operation-Oriented Thinking

  • "What can I use this operation on?"
  • Looking at the function type signature Shape -> number
  • FP-like, Haskell function composition

Neither is correct; they are tools to be used selectively based on the problem domain or individual thinking style.

Practical Guidelines

A practical approach when using discriminated unions in TypeScript:

  1. Place types and functions in the same file to increase cohesion.
  2. Use pipe to write in a data-oriented way if the transformation occurs only once.
  3. Use flow to compose functions if the transformation is reusable.
  4. Naive nesting is sufficient for simple cases.
// domain/order.ts
type Order = Draft | Paid | Shipped

const ship = (o: Paid): Shipped => { ... }
const cancel = (o: Draft | Paid): Cancelled => { ... }
const toSummary = (o: Order): string => { ... }

export { Order, ship, cancel, toSummary }

This file configuration centralizes "what can be done to the Order type." Syntactically, they are functions, but conceptually, they possess the same degree of cohesion as an OOP class.

Conclusion: Design Consistency Beyond Syntax

Rather than a binary opposition between OOP and functional programming, it is important that the same design principles can be applied regardless of which syntax you use.

  • Cohesion: Place related data and operations close together.
  • Coupling: Minimize dependencies between modules.
  • Expression Problem: Design with the direction of extension in mind.

"The position of the subject" is a syntactic choice; the underlying design philosophy—the relationship between data and operations, the scope of ripple effects, and module boundaries—is common.

Choose the syntax that fits your thinking style while maintaining design consistency. That, I believe, is a practical approach that transcends paradigms.

GitHubで編集を提案

Discussion