The trade-off is between ease of extension in two cases: - adding new types to the sum type / new subclasses - adding new methods that can operate on all types / subclasses
In a classic OO design, it's easy for any client to add new subclasses that implement the same API as the existing classes. However, adding a new API means that all subclasses need to be changed.
Conversely, in an FP design, adding a new type to the sum type (a new enum value) means that all places pattern matching on the sum types (switching on the enum) need to be changed. However, adding a new operation that works with the existing types is trivial.
To give a more specific example, let's say we want to model an expression tree.
An OO design might look like this:
abstract class BaseExpression {
abstract evaluate()
subexpressions()
}
class SumExpression extends BaseExpression {
evaluate() = map(evaluate, subexpressions()).Sum()
}
class NumberExpression extends BaseExpression {
int x
subexpressions() = [x]
evaluate() = x
}
An FP design might look like type ExpressionTree a = SumExpresssion [ExpressionTree] | NumberExpression a
evaluate :: ExpressionTree a -> a
evaluate SumExpression xs = sum map evaluate xs
evaluate NumberExpression x = x
subexpressions :: ExpressionTree a -> [a]
subexpressions SumExpression xs = map union xs
subexpressions NumberExpression x = [x]
Equivalently, an enum based design would have enum ExprType {
Sum
Number
}
struct SumExpression {
ExprType
*void[] Subexpressions
}
struct NumberExpression {
ExprType
int x
}
evaluate(e) {
switch(e->ExprType) {
case Sum: (SumExpression)e.Subexpressions.map(evaluate).Sum()
case Number: (NumberExpression)e.x
}
}
subexpressions(e) {
switch(e->ExprType) {
case Sum: return (SumExpression)e.subexpressions
case Number: void*[]{(NumberExpression)e.x}
}
}
Now, if we want to add support for MultiplyExpression, in the OO program we add a new file and we define evaluate() for MultiplyExpression. In the FP program we have to modify the definitions of ExpressionTree, SumExpression and NumberExpression.Conversely, if we want to add support to print an ExpressionTree, in the FP version we just add a new function in a new file and describe how to print each type of ExpressionTree. In the OO program, we need to modify the implementations of each existing BaseExpression subclass to add support for printing.