- Courses
- đ»Programming Languages
- đ«OCaml (WIP)
- Object-Oriented Programming
- Objects vs Modules & Functors
On this page
OCaml Objects vs Modules & Functors: When to Use Each
Published on September 19, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
OCaml provides two distinct mechanisms for abstraction and code reuse: the object system (classes, objects, inheritance) and the module system (modules, signatures, functors). The choice between them is not a matter of taste but of which kind of extensibility a problem requires. Objects excel when the set of operations is fixed but the set of implementations is open. Modules and functors excel when the set of implementations is fixed but the set of operations is open. This dual relationship is the expression problem, and understanding it is the key to making the right architectural decision.
The Expression Problemâ
The expression problem, named by Philip Wadler, describes a fundamental tension in programming language design. Consider a data type representing expressionsâa small language with variables, constants, addition, and multiplication. Two kinds of extension are possible. Datatype extensibility adds a new variant to the data type, such as a subtraction expression. Functional extensibility adds a new operation on the data type, such as pretty-printing or free-variable analysis.
A well-designed solution should satisfy three conditions: code-level modularization, so that new variants and new operations live in separate files; separate compilation, so that these files can be compiled and distributed independently; and static type safety, so that no type checking guarantees are lost.
The functional/modular model of OCaml handles functional extensibility with ease. Adding a new function that pattern-matches on an existing variant type is straightforward and requires no changes to the type definition or to existing functions. Datatype extensibility, however, is difficult: adding a new constructor to a regular variant requires modifying the type definition and every function that matches on it.
The object model reverses this tradeoff. Adding a new subclass that overrides methods is easy and requires no changes to existing code. Adding a new method to an existing class, however, requires modifying every class in the hierarchy that inherits from it. In the object model, one can extend the objects but not the methods; in the functional/modular model, types are not extensible but one can create new functions on the types. In this respect, the two models are duals.
When Objects Genuinely Helpâ
Objects are the right tool when the set of operations is fixed but the set of implementations is open. This occurs in several recurring scenarios.
Open Implementations with Fixed Operationsâ
A plugin architecture is the canonical example. The host application defines a fixed interfaceâsay, a Plugin class with methods name, initialize, and execute. New plugins are added by defining new subclasses that override these methods. The host application never changes. The set of operations is fixed by the abstract class, but the set of implementations grows without bound.
This pattern is difficult to express with functors, because functors require the entire module structure to be known at functor application time. Adding a new plugin would require either recompiling the host application with a new functor application or using first-class modules, which introduce their own overhead and complexity.
Structural Subtyping and Heterogeneous Collectionsâ
Objects support structural subtyping. An object type is determined by the methods it provides, not by its class ancestry. This means that a function can accept any object that provides the required methods, regardless of its class. Heterogeneous collections become possible: a list of shape objects can contain circles, rectangles, and triangles, each coerced to the shape type.
The OCaml manual notes that this extension of the ML type system cannot be simulated in pure ML. It is impossible to construct heterogeneous lists without breaking the type system. Modules do not provide this form of ad-hoc polymorphism. A functor application produces a module with a concrete type, and different functor applications produce incompatible types, even if the modules have identical structures.
Late Binding and Self-Referenceâ
Objects provide late binding: method calls are resolved at runtime based on the actual class of the object. This is essential for the open implementation pattern, where a base class defines a method in terms of other methods that subclasses may override. The self reference allows a method to call other methods on the same object, and late binding ensures that the subclass's overridden version is invoked.
The OCaml manual describes this as "inclusion/subtype polymorphism (sending of messages) thanks to late binding and subtyping, with restrictions due to equality, facilitating incremental programming". Modules do not support late binding; a module's functions are bound at compile time, and a functor application produces a module whose functions are fixed.
Modeling Existing Object-Oriented APIsâ
Objects are also useful for modeling existing object-oriented APIs. The OCaml community has used objects to model the DOM API in js_of_ocaml and BuckleScript, and the GTK API in Lablgtk. When the external API is inherently object-oriented, with inheritance hierarchies and method dispatch, using OCaml objects provides a natural mapping.
When Modules and Functors Are Betterâ
Modules and functors are the better tool when the set of implementations is fixed but the set of operations is open. This is the more common case in most OCaml codebases.
Adding New Functions to Existing Typesâ
The most common form of extension in functional programming is adding a new function that operates on an existing data type. With modules and variant types, this is trivial. Define the function, pattern-match on the variant constructors, and you are done. No existing code needs to change.
The OCaml manual states that "modular programming allows one to restrict parametric polymorphism and use immediate binding, which can be useful for conserving efficiency of execution". This efficiency comes from the fact that module functions are bound statically. There is no dispatch table lookup, no indirection through a method slot. The compiler can inline module functions and perform other optimizations that are impossible with method dispatch.
Type Abstraction and Encapsulationâ
Modules provide stronger abstraction guarantees than objects. A module signature can hide type definitions entirely, exposing only an abstract type and the operations on it. This is the foundation of the Set.Make and Map.Make functors: the tree representation is hidden, and users cannot construct sets or maps except through the module's operations.
Objects cannot contain type definitions. A class can define instance variables and methods, but it cannot export a type that other modules can use. This limitation means that objects are unsuitable for building generic data structures where the element or key type must be abstract.
Functors as Parameterized Modulesâ
Functors provide the most powerful generalization mechanism in OCaml. A functor is a function from modules to modules, allowing a module to be parameterized by another module. This is how Set.Make is parameterized by an OrderedType module. The resulting set module is specialized to the element type, and the comparison function is bound at functor application time.
This binding at application time means that every operation on the set uses the same comparison function consistently. There is no way to accidentally use a different comparison function, because the set type is abstract and the comparison function is not exposed. Objects do not provide this guarantee: a method that compares elements might be overridden by a subclass with a different comparison, leading to inconsistent behavior.
Performanceâ
Method invocation in OCaml uses dynamic dispatch, which involves looking up the method in a dispatch table and invoking the resulting function. This indirection is what enables late binding and subtyping, but it has a measurable cost. The OCaml manual's benchmark shows that for 10 million iterations, method dispatch takes 7.5 seconds in bytecode and 0.6 seconds in native code, while a direct function call takes 6.0 seconds in bytecode and 0.3 seconds in native code.
More recent benchmarks confirm this gap. On a Phenom II processor, 100 million iterations of an object method took 6.073 seconds, while the equivalent record-based operation took 3.078 seconds and the module-based operation took 1.881 seconds. Method dispatch is roughly three times slower than a direct function call in this benchmark.
The Flambda optimizer, OCaml's native compiler backend, does not inline method calls to objects. It does inline functor applications at toplevel and can inline first-class module calls when the particular function is known. This means that module-based code benefits from inlining and other optimizations that object-based code does not.
The Dual Relationship in Practiceâ
The expression problem is not a problem to be solved once and for all. It is a description of a fundamental tradeoff. OCaml's advantage is that it provides both models, allowing the programmer to choose the most appropriate one for each part of a program.
A practical guideline emerges from this analysis. Use objects when you need to model a family of related behaviors that share a common interface but differ in implementation, and when new implementations are expected to be added over time. Use modules and functors when you need to build generic data structures, when type abstraction is required, when performance is critical, or when the primary form of extension is adding new functions to existing types.
The OCaml community's practical experience supports this guideline. Most OCaml codebases use modules over classes. A class is useful when you need inheritance, for example with widgets or plugin systems. In most other cases, modules and functors provide better tools for the task.
A Concrete Example: Shapesâ
Consider a program that manipulates geometric shapes. The program needs to compute the area and perimeter of circles, rectangles, and triangles, and it needs to iterate over a heterogeneous collection of shapes.
With objects, the design is natural. Define an abstract shape class with virtual methods area and perimeter. Define subclasses circle, rectangle, and triangle. Each subclass implements the methods. A heterogeneous list of shapes is a shape list, and iterating over it calls the appropriate method for each shape via dynamic dispatch.
With modules and functors, the design requires more restructuring. Define a SHAPE signature with area and perimeter functions. Define a functor that produces a shape module given the shape's parameters. Define separate modules for each shape. To create a heterogeneous collection, you need a variant type that wraps each shape module, or you need first-class modules. The result is more verbose and involves more boilerplate.
However, if the program needs to add a new operation, such as computing the bounding box, the tradeoff reverses. With objects, adding a bounding_box method requires modifying the abstract shape class and every subclass. With modules, adding a bounding_box function that pattern-matches on the shape variant requires only one new function and no changes to existing code.
Common Pitfalls in Choosingâ
The first pitfall is assuming that objects are inherently better because they are familiar from other languages. OCaml's module system is more powerful than most, and the functional/modular model is often the better choice even when an object-oriented design seems natural.
The second pitfall is using objects for performance-critical code without measuring. The three-to-ten-fold overhead of method dispatch can be significant in tight loops. If profiling shows that method dispatch is a bottleneck, rewriting the component with modules or records may yield a substantial speedup.
The third pitfall is using modules when structural subtyping or late binding is genuinely required. Fighting the module system to simulate dynamic dispatch is usually a sign that objects are the right tool. First-class modules can provide some of this flexibility, but they introduce runtime overhead and are more complex than objects for this use case.
The fourth pitfall is mixing objects and modules without a clear rationale. OCaml allows both, but a codebase that uses both without a principled distinction becomes harder to understand. The expression problem provides a principled distinction: use objects when implementations are open, use modules when operations are open.
Key Takeawaysâ
OCaml provides two models for abstraction and code reuse, and they are duals with respect to the expression problem. Objects favor open implementations with fixed operations, structural subtyping, late binding, and heterogeneous collections. Modules and functors favor open operations with fixed implementations, type abstraction, static binding, and performance. The choice is not a matter of taste but of which kind of extensibility a problem requires. Objects are the right tool for plugin architectures, heterogeneous hierarchies, and modeling existing object-oriented APIs. Modules and functors are the right tool for generic data structures, type-safe abstractions, and performance-critical code. Understanding this dual relationship enables the programmer to make deliberate architectural decisions rather than defaulting to one model out of habit.
Frequently Asked Questionsâ
What is the expression problem in OCaml?
The expression problem describes the tension between two kinds of extensibility: adding new data type variants and adding new operations on those variants. Modules handle adding new operations well but struggle with new variants. Objects handle adding new implementations well but struggle with new operations. OCaml provides both models, allowing the programmer to choose.
When should I use objects instead of modules in OCaml?
Use objects when the set of operations is fixed but the set of implementations is open, when structural subtyping or heterogeneous collections are required, when late binding is necessary, or when modeling an existing object-oriented API. Use modules when the set of implementations is fixed but the set of operations is open, when type abstraction is needed, or when performance is critical.
Are OCaml objects slower than modules?
Yes. Method invocation uses dynamic dispatch, which involves a dispatch table lookup. Benchmarks show that object method calls can be three times slower than direct function calls or module function calls. The Flambda optimizer does not inline method calls to objects. For performance-critical code, modules and functors are preferable.
Can objects and modules be mixed in OCaml?
Yes. OCaml allows both to coexist. A common pattern is to define modules and use functors as factories that produce objects of particular types. This combines the type abstraction and static binding of modules with the late binding and subtyping of objects where needed.
Why does OCaml have both objects and modules?
The two models are duals with respect to the expression problem. Modules favor adding new operations to existing types. Objects favor adding new implementations of existing operations. By providing both, OCaml allows the programmer to choose the model that fits the problem, and to mix them to overcome the limitations of each.
What is the performance cost of object method dispatch in OCaml?
Method dispatch involves an indirection through a method table. The exact cost depends on the code and the compiler backend. Benchmarks show that 100 million method calls can take roughly 6 seconds on older hardware, compared to 3 seconds for record field access and 2 seconds for module function calls. Native compilation reduces the absolute cost but does not eliminate the indirection.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Inheritance and Structural Subtyping
Next
Exercise: Objects vs Modules
-
The Expression Problem
-
When Objects Genuinely Help
- Open Implementations with Fixed Operations
- Structural Subtyping and Heterogeneous Collections
- Late Binding and Self-Reference
- Modeling Existing Object-Oriented APIs
-
When Modules and Functors Are Better
- Adding New Functions to Existing Types
- Type Abstraction and Encapsulation
- Functors as Parameterized Modules
- Performance
-
The Dual Relationship in Practice
-
A Concrete Example: Shapes
-
Common Pitfalls in Choosing
-
Key Takeaways
-
Frequently Asked Questions
