Posts Tagged ‘FunctionalProgramming’
[DevoxxFR2013] Objects and Functions: Conflict Without a Cause?
Lecturer
Martin Odersky is a professor at EPFL in Lausanne, Switzerland, specializing in programming languages that blend object-oriented and functional paradigms. His research unifies these approaches, evidenced by designs like Pizza, GJ, and Functional Nets. He co-designed Java generics and authored the original javac compiler. Currently, he focuses on Scala, fusing functional and object-oriented programming while ensuring interoperability with Java and .NET.
Abstract
Martin Odersky’s lecture traces object-oriented programming’s (OOP) rise, parallels it with functional programming’s (FP) resurgence, and argues for their synthesis. Analyzing historical catalysts, methodological benefits, and modern hardware demands, he demonstrates how FP addresses parallelism and reactivity challenges. Through Scala examples, Odersky shows OOP and FP as complementary, enhancing modularity and abstraction without mutual exclusion.
Historical Roots and Catalysts for OOP Adoption
Odersky recounts his journey from Pascal compilers to modular languages, Java involvement, and Scala creation. OOP’s mainstreaming, he argues, stemmed not from encapsulation or reuse but practical necessities. Simula (1967) for simulations and Smalltalk (late 1970s) for GUI widgets inverted traditional data structures: fixed operations, unbounded implementations.
In procedural languages like C, this was cumbersome via function pointers; OOP simplified dynamic binding for unknown implementations. Odersky notes early confusion with Smalltalk, mirroring current FP bewilderment. OOP’s advantages – modeling, dependency inversion – emerged post-adoption, sparked by widget programming appeal.
Functional Programming’s Resurgence and Methodological Strengths
FP offers fewer errors, superior modularity, and productivity via higher abstractions and shorter code. Yet, despite 50-year existence, mainstream adoption lagged. Odersky identifies multicore and cloud computing as catalysts: parallelism for hardware utilization, reactivity for asynchronous events, distribution for delays/failures.
Mutable state exacerbates issues like cache coherence and non-determinism in concurrent environments. Immutable data mitigates races, enabling safe caching. Locks/threads scale poorly; even transactions retain problems. FP’s immutability fosters determinism, crucial for scalable systems.
Addressing Modern Computing Challenges with FP
Odersky outlines a triple challenge: parallel, reactive, distributed programming. Mutable state hinders each; FP excels by avoiding it.
For parallelism, he exemplifies mapping developer names: sequential in Scala, parallel via .par, yielding a parallel collection. Side effects risk chaos due to reordered executions, necessitating functional purity for correctness.
Reactivity example: an online store querying users, orders, products, stock. Synchronous calls block threads on slow services, degrading performance. Asynchronous futures prevent blocking; Scala’s for-comprehensions compose them elegantly, hiding complexity. Refactoring for parallelism pairs futures, executing concurrently.
For-comprehensions translate universally to map, flatMap, filter, allowing library-defined interpretations – sequential or async – without polluting domain logic.
Synthesizing OOP and FP: Beyond False Dichotomies
Communities often view OOP and FP oppositely, but Odersky argues orthogonality. Objects modularize (“what goes where”), providing containers with dynamic binding and inheritance. Essential for large codebases (e.g., million-line Scala systems), they prevent global namespace chaos – a Haskell limitation.
Redefine objects: eliminate mutable state dogma (e.g., immutable java.lang.String), structural equality over identity, focus on behavior. Scala embodies this fusion, modeling algebraic types with objects while importing FP capabilities.
Scala unifies scripting (winning JavaOne Script Bowl) and safe, performant systems (core for Twitter, LinkedIn). Odersky concludes OOP/FP synergy enhances development, urging exploration via Scala Days, courses, and talks.
Relevant Links and Hashtags
Links:
[DevoxxBE2012] First Steps with Scala (Part 1/2)
In an engaging session, Dick Wall and Bill Venners, co-founders of Escalate Software and prominent figures in the Scala community, introduced newcomers to the Scala programming language. Dick, known for his JavaPosse involvement, and Bill, president of Artima and author of key Java texts, adapted their training curriculum to cover foundational elements. Their approach fused object-oriented and functional paradigms, emphasizing Scala’s blend of familiarity and innovation.
They commenced with the Scala REPL, a tool they use daily for experimentation. This interactive shell allows immediate code execution, inferring types and storing results for reuse, making it invaluable even for Java developers exploring libraries.
Dick and Holly—wait, Dick and Bill—highlighted Scala’s strong typing with inference, reducing boilerplate while maintaining safety. They demonstrated basic operations, showing how everything integrates into a unified hierarchy, unlike Java’s primitives and references.
Defining Variables and Immutability
Transitioning to variables, Dick and Bill distinguished between vals (immutable) and vars (mutable), promoting vals for reliability. This design choice encourages constant use without extra syntax, contrasting Java’s final keyword. They illustrated reassignment errors, noting REPL’s scoping allows redefinitions, mimicking nested blocks.
Type specifications, optional due to inference, follow names with colons, inverting Java’s order for natural flow. Examples showed string inferences and explicit declarations, underscoring flexibility.
They addressed mutability choices, advising private volatile vars for necessary changes, or mutable objects within immutable structures, depending on context.
Control Structures and Expressions
Dick and Bill explored control structures, revealing Scala’s expression-oriented nature. If statements return values, enabling concise assignments without ternaries. While loops, though imperative, yield Unit, encouraging functional alternatives.
For comprehensions, powerful for iteration, support guards and yields, transforming collections declaratively. They demonstrated filtering even numbers or yielding transformed lists, highlighting pattern matching integration.
Try-catch blocks, also expressions, handle exceptions functionally, with finally clauses for cleanup. This uniformity simplifies code, treating controls as value producers.
Functions and Closures
Delving into functions, they defined them as objects, enabling higher-order usage. Simple defs showed parameter typing and inference, with return types often omitted.
Function literals, akin to lambdas, capture environments as closures, allowing deferred execution. Examples illustrated anonymous functions for mapping or filtering, emphasizing Scala’s functional leanings.
They introduced by-name parameters for lazy evaluation, useful in custom controls like loops, mimicking built-in syntax without special privileges.
Collections and Functional Programming
Scala collections, immutable by default, support transformations via methods like map and filter. Dick and Bill showcased creating lists, accessing elements, and applying operations, yielding new collections without mutation.
They contrasted mutable variants, advising caution for concurrency. For comprehensions over collections generate new ones, combining iteration with functional purity.
Approaching functional style, they encouraged avoiding side effects, using recursion or folds for aggregations, fostering predictable code.
Advanced Basics and Q&A Insights
In Q&A, they addressed optimizations: Scala uses primitives internally, with @specialized for generics avoiding boxing. Profiling mirrors Java tools, with quirks in coverage.
Dick and Bill wrapped by previewing afternoon labs on Scala Koans, urging practice. Their session laid a solid groundwork, blending theory with practical demos, preparing attendees for Scala’s expressive power.