01: OOP vs FP with Java example – placing a trade

A Trade goes through 3 state changes – placed, filled, and settled. Let’s solve this simple problem using both OOP & FP approaches.

Place –> Fill –> Settle

OOP approach by mutating the state

State changes are maintained via a variable named “status“, which is mutable. Here is the “OrderService.java”, which has both state & behavior.

Finally, let’s use the class with the main method that takes a “Trade” from initial to settled states.

Output:

FP approach with type classes & composing functions

InitialOrder.java type class
FillOrder.java type class
SettleOrder.java type class
Main class that composes the “execute” functions across the type classes

Output:

Slightly modified version with a BiFunction

This takes an instance of the “InitialOrder” via the “apply” function of the “BiFunction”, which takes two inputs.

Output:

Analyze the differences

1) The OOP mutates the states of the “OrderService”‘s status variable, whereas the FP approach creates a new object to capture the new state without mutating. OOP had to test the internal states and throw exceptions if invoked with incorrect internal states.

2) OOP focuses on the “nouns” as in the statuses being INITIAL, FILLED, SETTLED, etc whereas the FP focuses on the “verb” execute().

3) The FP composes the individual functions, which do their own functionality to create an output. Functions in FP are specialized in performing a single task, hence compose better than the OOP approach. For example, the above code can be composed in different ways to get the same outcome.

Approach 1:
Approach 2:

300+ Java Developer Interview Q&As

800+ Java Interview Q&As

Top