From object oriented to functional domain modelingMario Fusco
This document discusses moving from an object-oriented approach to a functional approach for domain modeling. It provides examples of modeling a bank account and salary calculator in both OOP and FP styles. Some key benefits of the functional approach highlighted include immutability, avoiding side effects, handling errors through monads instead of exceptions, and composing functions together through currying and composition. Overall the document advocates that while OOP and FP both have merits, modeling as functions can provide advantages in terms of understandability, testability, and extensibility of the code.
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
The document discusses functional programming concepts like higher-order functions, function composition, currying, and lazy evaluation. It provides examples of implementing strategies like converting between units using functions and creating streams of prime numbers lazily to avoid stack overflows. Tail call optimization is mentioned as a way to avoid stack overflows with recursive functions.
The document discusses monads and functional programming concepts. It begins by explaining that monads are structures that put values in computational contexts. It then provides a technical definition of a monad involving endofunctors, natural transformations, and laws. Several examples are given to illustrate monads, including the Optional monad in Java to handle null values, and the Stream monad to represent sequences. The document advocates using monads to make aspects like errors, state, and effects explicit in a program's type system.
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
The document discusses several key concepts in functional programming including:
- Immutable data and pure functions avoid side effects and allow for referential transparency.
- Higher order functions and avoiding mutable state enable concurrency and parallelism without data races.
- Programs can be designed with a pure functional core and push side effects to the outer layers for modularity.
Modularizing a project is never easy, a lot of files to move and the dependencies between them is not always what we expect. Then the Dagger configuration used in a single module project often doesn't scale well to a multi module project. Hilt is opinionated about the configuration to use (we don't need to argue anymore about using component dependencies or subcomponents!) and this configuration works perfectly even in a multi module project. In this talk we'll see first an introduction to Hilt and a comparison with Dagger to understand why it's easier to configure. Then we'll see how to leverage it in a multi module project (both in a standard layered architecture and in a Clean Architecture that uses the Dependency Inversion) to improve build speed and code testability. Spoiler alert: using sample apps that include a single feature in the app helps a lot!
This document provides an overview of the Django web framework. It begins with definitions of Django and its model-view-template architecture. It then discusses Django's design philosophies of being loosely coupled, encouraging less coding through the DRY principle, and enabling fast development. The document outlines how to set up a Django environment, create a project and apps, develop views, integrate templates, and link everything together through URLs. In summary, it serves as a seminar covering the basic concepts and processes for building websites using the Django web framework in Python.
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
This document summarizes a presentation about functional programming and how functions like map(), flatMap(), and reduce() can simplify collection processing, concurrency, and big data problems. The presentation introduces functional programming concepts and how languages like Java 8 have adopted these with features like lambda expressions and streams. It provides examples of how to use streams to map, filter, and reduce collections in a more declarative way compared to imperative for loops. It also discusses how functions and futures can help simplify concurrent operations by allowing asynchronous work to be expressed more clearly.
Java 8 Stream API. A different way to process collections.David Gómez García
A look on one of the features of Java 8 hidden behind the lambdas. A different way to iterate Collections. You'll never see the Collecions the same way.
These are the slides I used on my talk at the "Tech Thursday" by Oracle in June in Madrid.
The document discusses clean coding practices for Java developers. It covers topics such as choosing meaningful names for variables, methods, and classes; writing code that is easy for others to understand; breaking methods down into single logical steps; and using fluent APIs to make code more readable. The presentation provides examples of clean code and ways to refactor code to follow best practices.
This presentation introduces some concepts about the Java Collection framework. These slides introduce the following concepts:
- Collections and iterators
- Linked list and array list
- Hash set and tree set
- Maps
- The collection framework
The presentation is took from the Java course I run in the bachelor-level informatics curriculum at the University of Padova.
Django is a high-level Python web framework that encourages rapid development and clean design. It makes building web apps faster with less code by providing models, templates, views, and URL patterns. To build a project, you create a project folder using startproject, then add apps using startapp which contain models, views, and other files. You sync the database, configure URLs and views, then run the development server to view your new app.
This document provides an overview of Java Swing components. It defines Swing as a GUI toolkit built on top of AWT that provides platform-independent and lightweight components. It describes common Swing components like JButton, JTextField, JTextArea and their usage. It also compares AWT and Swing, explaining how Swing components are more powerful and support pluggable look and feel while AWT is platform-dependent. Examples are given to demonstrate creating and using Swing components like JButton, JTextField, JTextArea etc.
Presentation provides introduction and detailed explanation of the Java 8 Lambda and Streams. Lambda covers with Method references, default methods and Streams covers with stream operations,types of streams, collectors. Also streams are elaborated with parallel streams and benchmarking comparison of sequential and parallel streams.
Additional slides are covered with Optional, Splitators, certain projects based on lambda and streams
This document provides an introduction to web development with the Django framework. It outlines Django's project structure, how it handles data with models, and its built-in admin interface. It also covers views, templates, forms, and generic views. Django allows defining models as Python classes to represent the database structure. It provides a production-ready admin interface to manage data. URLs are mapped to views, which can render templates to generate responses. Forms validate and display data. Generic views handle common tasks like displaying object lists.
The document discusses several core Java concepts including:
1) Comments in Java code can be single-line or multiline javadoc comments.
2) Classes are fundamental in Java and describe data objects and methods that can be applied to objects.
3) Variables and methods have scopes determined by curly braces and a variable is only available within its scope.
The document discusses method overloading and overriding in .NET. Method overloading allows a method to have the same name but different parameters within a class. Method overriding involves a subclass redefining a method from its parent class with the same name and parameters. The key differences are that overloading is resolved at compile-time based on parameters, while overriding is resolved at run-time based on the object's type. Overriding changes existing functionality, while overloading adds or extends functionality.
Collections in Java include arrays, iterators, and interfaces like Collection, Set, List, and Map. Arrays have advantages like type checking and known size but are fixed. Collections generalize arrays, allowing resizable and heterogeneous groups through interfaces implemented by classes like ArrayList, LinkedList, HashSet and HashMap. Common operations include adding, removing, and iterating over elements.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
- HTML, CSS, and JavaScript are becoming the new standard for building applications and interactive experiences on the web.
- Best practices include using semantic HTML, clean CSS with a focus on maintainability, and JavaScript performance optimizations.
- Key techniques discussed are image sprites, progressive enhancement, and jQuery selector chaining to reduce DOM lookups.
The document discusses static vs instance methods and variables in Java. Static methods and variables have a single copy associated with the class, while instance methods and variables are associated with each object. Static blocks allow initialization of static variables and run when the class is loaded. Static classes cannot be inherited and can only contain a static constructor. Methods are functions in object-oriented programming that perform operations on objects or classes.
ReactJS for Beginners provides an overview of ReactJS including what it is, advantages, disadvantages, typical setup tools, and examples of basic React code. Key points covered include:
- ReactJS is a JavaScript library for building user interfaces and is component-based.
- Advantages include high efficiency, easier JavaScript via JSX, good developer tools and SEO, and easy testing.
- Disadvantages include React only handling the view layer and requiring other libraries for full MVC functionality.
- Examples demonstrate basic components, properties, events, conditional rendering, and lists in ReactJS.
Functions in C can be defined by the user or come from standard libraries. User-defined functions must be declared with a name, return type, and parameters. Functions are called by passing actual arguments which are assigned to formal parameters. Arguments can be passed by value, where copies are used, or by reference, where the function accesses the original variables. Recursion is when a function calls itself, reducing the problem size each time until a base case is reached.
This is a good opportunity for those who want to learn Selenium and wondering where to start from. This presentation covers the topics related to Selenium IDE and locators. This would help in understanding the more complex Selenium Webdriver that will be taken up in next session.
The document discusses different approaches to object-oriented programming in JavaScript, including classical and prototypal inheritance, constructor functions, and the prototype property. It explains how prototypal inheritance works by linking objects together through their internal prototype properties. Constructor functions and the new operator allow simulating classical inheritance by establishing prototype links. Various design patterns are also covered, such as public/privileged methods, singletons, modules, and parasitic inheritance.
The document provides information on object-oriented programming concepts in Java including classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It defines classes like Shape, Rectangle, Circle and Triangle to demonstrate these concepts. It also discusses Java data types, constructors, access modifiers, interfaces and abstract classes.
This document provides an overview of Angular, including:
- Angular is a JavaScript framework used to build client-side applications with HTML. Code is written in TypeScript which compiles to JavaScript.
- Angular enhances HTML with directives, data binding, and dependency injection. It follows an MVC architecture internally.
- Components are the basic building blocks of Angular applications. Modules contain components and services. Services contain reusable business logic.
- The document discusses Angular concepts like modules, components, data binding, services, routing and forms. It provides examples of creating a sample login/welcome application in Angular.
Asynchronous API in Java8, how to use CompletableFutureJosé Paumard
Slides of my talk as Devoxx 2015. How to set up asynchronous data processing pipelines using the CompletionStage / CompletableFuture API, including how to control threads and how to handle exceptions.
The document discusses the introduction and advantages of lambda expressions and functional programming in Java 8. Some key points include:
- Lambda expressions allow passing behaviors as arguments to methods, simplifying code by removing bulky anonymous class syntax. This enables more powerful and expressive APIs.
- Streams provide a way to process collections of data in a declarative way, leveraging laziness to improve efficiency. Operations can be pipelined for fluent processing.
- Functional programming with immutable data and avoidance of side effects makes code more modular and easier to reason about, enabling optimizations like parallelism. While not natively supported, Java 8 features like lambda expressions facilitate a more functional approach.
The document discusses clean coding practices for Java developers. It covers topics such as choosing meaningful names for variables, methods, and classes; writing code that is easy for others to understand; breaking methods down into single logical steps; and using fluent APIs to make code more readable. The presentation provides examples of clean code and ways to refactor code to follow best practices.
This presentation introduces some concepts about the Java Collection framework. These slides introduce the following concepts:
- Collections and iterators
- Linked list and array list
- Hash set and tree set
- Maps
- The collection framework
The presentation is took from the Java course I run in the bachelor-level informatics curriculum at the University of Padova.
Django is a high-level Python web framework that encourages rapid development and clean design. It makes building web apps faster with less code by providing models, templates, views, and URL patterns. To build a project, you create a project folder using startproject, then add apps using startapp which contain models, views, and other files. You sync the database, configure URLs and views, then run the development server to view your new app.
This document provides an overview of Java Swing components. It defines Swing as a GUI toolkit built on top of AWT that provides platform-independent and lightweight components. It describes common Swing components like JButton, JTextField, JTextArea and their usage. It also compares AWT and Swing, explaining how Swing components are more powerful and support pluggable look and feel while AWT is platform-dependent. Examples are given to demonstrate creating and using Swing components like JButton, JTextField, JTextArea etc.
Presentation provides introduction and detailed explanation of the Java 8 Lambda and Streams. Lambda covers with Method references, default methods and Streams covers with stream operations,types of streams, collectors. Also streams are elaborated with parallel streams and benchmarking comparison of sequential and parallel streams.
Additional slides are covered with Optional, Splitators, certain projects based on lambda and streams
This document provides an introduction to web development with the Django framework. It outlines Django's project structure, how it handles data with models, and its built-in admin interface. It also covers views, templates, forms, and generic views. Django allows defining models as Python classes to represent the database structure. It provides a production-ready admin interface to manage data. URLs are mapped to views, which can render templates to generate responses. Forms validate and display data. Generic views handle common tasks like displaying object lists.
The document discusses several core Java concepts including:
1) Comments in Java code can be single-line or multiline javadoc comments.
2) Classes are fundamental in Java and describe data objects and methods that can be applied to objects.
3) Variables and methods have scopes determined by curly braces and a variable is only available within its scope.
The document discusses method overloading and overriding in .NET. Method overloading allows a method to have the same name but different parameters within a class. Method overriding involves a subclass redefining a method from its parent class with the same name and parameters. The key differences are that overloading is resolved at compile-time based on parameters, while overriding is resolved at run-time based on the object's type. Overriding changes existing functionality, while overloading adds or extends functionality.
Collections in Java include arrays, iterators, and interfaces like Collection, Set, List, and Map. Arrays have advantages like type checking and known size but are fixed. Collections generalize arrays, allowing resizable and heterogeneous groups through interfaces implemented by classes like ArrayList, LinkedList, HashSet and HashMap. Common operations include adding, removing, and iterating over elements.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
- HTML, CSS, and JavaScript are becoming the new standard for building applications and interactive experiences on the web.
- Best practices include using semantic HTML, clean CSS with a focus on maintainability, and JavaScript performance optimizations.
- Key techniques discussed are image sprites, progressive enhancement, and jQuery selector chaining to reduce DOM lookups.
The document discusses static vs instance methods and variables in Java. Static methods and variables have a single copy associated with the class, while instance methods and variables are associated with each object. Static blocks allow initialization of static variables and run when the class is loaded. Static classes cannot be inherited and can only contain a static constructor. Methods are functions in object-oriented programming that perform operations on objects or classes.
ReactJS for Beginners provides an overview of ReactJS including what it is, advantages, disadvantages, typical setup tools, and examples of basic React code. Key points covered include:
- ReactJS is a JavaScript library for building user interfaces and is component-based.
- Advantages include high efficiency, easier JavaScript via JSX, good developer tools and SEO, and easy testing.
- Disadvantages include React only handling the view layer and requiring other libraries for full MVC functionality.
- Examples demonstrate basic components, properties, events, conditional rendering, and lists in ReactJS.
Functions in C can be defined by the user or come from standard libraries. User-defined functions must be declared with a name, return type, and parameters. Functions are called by passing actual arguments which are assigned to formal parameters. Arguments can be passed by value, where copies are used, or by reference, where the function accesses the original variables. Recursion is when a function calls itself, reducing the problem size each time until a base case is reached.
This is a good opportunity for those who want to learn Selenium and wondering where to start from. This presentation covers the topics related to Selenium IDE and locators. This would help in understanding the more complex Selenium Webdriver that will be taken up in next session.
The document discusses different approaches to object-oriented programming in JavaScript, including classical and prototypal inheritance, constructor functions, and the prototype property. It explains how prototypal inheritance works by linking objects together through their internal prototype properties. Constructor functions and the new operator allow simulating classical inheritance by establishing prototype links. Various design patterns are also covered, such as public/privileged methods, singletons, modules, and parasitic inheritance.
The document provides information on object-oriented programming concepts in Java including classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It defines classes like Shape, Rectangle, Circle and Triangle to demonstrate these concepts. It also discusses Java data types, constructors, access modifiers, interfaces and abstract classes.
This document provides an overview of Angular, including:
- Angular is a JavaScript framework used to build client-side applications with HTML. Code is written in TypeScript which compiles to JavaScript.
- Angular enhances HTML with directives, data binding, and dependency injection. It follows an MVC architecture internally.
- Components are the basic building blocks of Angular applications. Modules contain components and services. Services contain reusable business logic.
- The document discusses Angular concepts like modules, components, data binding, services, routing and forms. It provides examples of creating a sample login/welcome application in Angular.
Asynchronous API in Java8, how to use CompletableFutureJosé Paumard
Slides of my talk as Devoxx 2015. How to set up asynchronous data processing pipelines using the CompletionStage / CompletableFuture API, including how to control threads and how to handle exceptions.
The document discusses the introduction and advantages of lambda expressions and functional programming in Java 8. Some key points include:
- Lambda expressions allow passing behaviors as arguments to methods, simplifying code by removing bulky anonymous class syntax. This enables more powerful and expressive APIs.
- Streams provide a way to process collections of data in a declarative way, leveraging laziness to improve efficiency. Operations can be pipelined for fluent processing.
- Functional programming with immutable data and avoidance of side effects makes code more modular and easier to reason about, enabling optimizations like parallelism. While not natively supported, Java 8 features like lambda expressions facilitate a more functional approach.
Functional Programming - Past, Present and FuturePushkar Kulkarni
Functional programming has evolved significantly since its origins in lambda calculus. Key developments include Lisp (1958), ML (1973), Haskell (1990), and more recently languages for the JVM like Scala (2004) and Clojure (2007). Functional concepts like immutable data, higher-order functions, lazy evaluation and currying allow a more declarative style and improved performance. Advances like tail call optimization and parallelism address early performance issues. Future areas include dependent types as in Idris and embracing functional principles in mainstream languages like Java 8. Functional programming changes how we think about solving problems.
Functional Programming Past Present FutureIndicThreads
Presented at the IndicThreads.com Software Development Conference 2016 held in Pune, India. More at http://www.IndicThreads.com and http://Pune16.IndicThreads.com
--
Programs written in functional programming languages, like Scala and Clojure, are less complex than their Java counterpart. They are easier to reason about once you have passed the initial learning curve for the language. Even though functional programming has become syntactically sane with the introduction of lambda, the functional languages still present competitive features such as tail call optimization, lazy evaluation and persistent data structures. These features can be implemented as Java libraries. You will see how they can radically reduce complexity of Java code, today.
Harnessing the Power of Java 8 Streams IndicThreads
Presented at the IndicThreads.com Software Development Conference 2016 held in Pune, India. More at http://www.IndicThreads.com and http://Pune16.IndicThreads.com
--
The document discusses Java 8 Lambdas and the Streaming API. Lambdas allow functions to be passed around as method arguments rather than whole objects. The Streaming API allows collections to be processed in a functional way using intermediate and terminal operations on a stream, such as filtering, mapping, reducing, and collecting the results. Examples demonstrate common stream operations like filtering, sorting, mapping elements to different types, and collecting results.
Laziness, trampolines, monoids and other functional amenities: this is not yo...Codemotion
by Mario Fusco - Lambdas are the main feature introduced with Java 8, but the biggest part of Java developers are still not very familliar with the most common functional idioms and patterns. The purpose of this talk is presenting with practical examples concepts like high-order functions, currying, functions composition, persistent data structures, lazy evaluation, recursion, trampolines and monoids showing how to implement them in Java and how thinking functionally can help us to design and develop more readable, reusable, performant, parallelizable and in a word better, code.
OOP and FP: become a better programmer - Simone Bordet, Mario Fusco - Codemot...Codemotion
The document discusses examples of applying object-oriented programming (OOP) and functional programming (FP) paradigms to programming tasks in Java. It provides multiple versions of examples using OOP vs FP styles. The goals are to show that both paradigms are useful and that programmers should understand both to write better code. Certain problems are better solved with one paradigm over the other, and guidelines can help decide which to apply. The conclusion advocates learning both OOP and FP to practice "poly-paradigm programming" rather than just using multiple languages.
OOP and FP - Become a Better ProgrammerMario Fusco
The story of Simon, an experienced OOP Java developer, exposed to the new lambda features of JDK 8. His friend Mario, a long-bearded FP geek, will try to convince him that FP can help him develop more readable and maintainable code. A journey into the discovery of the main new feature - lambda expressions - of JDK 8
The document discusses functional programming concepts such as pure functions, recursion, avoiding state mutation, and higher order functions. It provides examples of iterating code written iteratively and functionally in C#, and discusses techniques for eliminating if statements and side effects from functions to make them more functional. The document is intended as a guide for C# programmers to understand functional programming principles.
This document discusses the history and evolution of functional programming in Java, including lambda expressions and streams. It describes how lambda expressions allow passing behaviors as arguments to methods like normal data. This improves API design, opportunities for optimization, and code readability. Streams encourage a lazy, pipelined style and can execute operations in parallel. Functional idioms like immutability and pure functions help enforce correctness and isolation of side effects.
Introduction to Functional Programming and usage of basic constructs in Java 7 using Guava.
Further, the session introduces Reactive Systems architecture and design.
This document provides an overview of Java 8 lambda expressions. It begins with an introduction and background on anonymous classes in previous Java versions. The main topics covered include lambda syntax, lambda expressions vs closures, capturing variables in lambda expressions, type inference, and functional interfaces. It also discusses stream operations like filter, map, flatMap, and peek. Finally, it covers parallelism and how streams can leverage multiple cores to improve performance.
This presentation was given online in July 2017 and will be given at the NY Java SIG later this year. It progressively builds on Java 8 concepts using puzzles and coding to give students confidence in their Java 8 stream/lambda skills. Handouts and code in https://github.com/boyarsky/java-8-streams-by-puzzles
The Sieve of Eratosthenes - Part 1 - with minor correctionsPhilip Schwarz
In this slide deck we are going to see some examples of how the effort required to read an understand the Sieve of Eratosthenes varies greatly depending on the programming paradigm used to implement the algorithm.
We'll see code in Java, Scheme, Haskell and Scala.
This version of the deck contains some minor corrections (see errata section in first version for details)
In this slide deck we are going to see some examples of how the effort required to read an understand the Sieve of Eratosthenes varies greatly depending on the programming paradigm used to implement the algorithm.
We'll see code in Java, Scheme, Haskell and Scala.
Errata:
slide 10: "points asserts" should be "asserts"
slide 22,23,25: "// larger than that root.private static int" should be "// larger than that root"
slide 29: "three slides" should be "two slides"
slide 45,46,48,49: List.range(m,n + 1) should be List.range(2,maxValue + 1)
Kogito: cloud native business automationMario Fusco
The document discusses business automation in the cloud using Kogito. It begins with an introduction to business automation concepts like processes, rules, and workflows. It then provides an overview of Kogito, describing it as a cloud-native development, deployment and execution platform for business automation that uses technologies like Drools, jBPM, and Quarkus under the hood. The document also demonstrates a sample serverless workflow built with Kogito.
Let's make a contract: the art of designing a Java APIMario Fusco
The document discusses best practices for designing Java APIs. It emphasizes making APIs intuitive, consistent, discoverable and easy to use. Some specific tips include using static factories to create objects, promoting fluent interfaces, using the weakest possible types, supporting lambdas, avoiding checked exceptions and properly managing resources using try-with-resources. The goal is to design APIs that are flexible, evolvable and minimize surprises for developers.
How and why I turned my old Java projects into a first-class serverless compo...Mario Fusco
Mario Fusco discusses turning old Java rule engine projects into serverless components by refactoring them to run natively on GraalVM and integrate with Quarkus. He describes the limitations of ahead-of-time compilation with GraalVM, such as lack of dynamic classloading. He details refactoring Drools to use an executable model and removing dependencies on dynamic class definition. This allows Drools to natively compile on GraalVM. He also discusses integrating the refactored Drools with Quarkus.
The document discusses object-oriented programming (OOP) and functional programming (FP). It argues that OOP and FP are not opposites and can be effectively combined. It addresses common myths about FP, such as that it is new, hard, or only suitable for mathematical problems. The document also compares how OOP and FP approach concepts like decomposition, composition, error handling, and mutability/referential transparency. While both approaches have merits, the document concludes there is no single best approach and the choice depends on the problem and programmer preferences.
The document provides an overview of key features and internals of the Drools 6 rule engine, including:
- The Phreak algorithm, which is faster than ReteOO and uses set-based propagation for improved performance on large data sets.
- The deployment model which uses kjar modules that are self-contained, versioned JAR files containing rules, models, and configuration. This allows for incremental compilation and use of the KieScanner for automatic updates.
- Changes to type declarations which are now compiled into the kjar, allowing them to be used directly in Java code without reflection.
Comparing different concurrency models on the JVMMario Fusco
This document compares different concurrency models on the JVM, including the native Java concurrency model based on threads, semaphores, and locks. It discusses the pros and cons of threads and locks, including issues around non-determinism from shared mutable state. Functional programming with immutable data and internal iteration is presented as an alternative that allows for free parallelism. The document also covers actors and their message passing approach, as well as software transactional memory.
Why we cannot ignore Functional ProgrammingMario Fusco
The document discusses several key concepts in functional programming including:
1) Pure functions that are referentially transparent and have no side effects like modifying variables or data structures.
2) Immutable data and persistent data structures that allow for sharing without synchronization.
3) Separating computational logic from side effects improves modularity and allows for parallelization.
4) A pure functional core can be wrapped with functions that have side effects to push effects to the outer layers.
Real world DSL - making technical and business people speaking the same languageMario Fusco
This document discusses domain specific languages (DSLs). It defines a DSL as a computer programming language with limited expressiveness focused on a particular domain to improve communication. The document discusses why DSLs are used to improve communication and maintainability. It also covers different types of DSLs, including internal and external DSLs. Examples of DSLs like Hibernate queries, jMock, and lambdaj are provided to illustrate DSL design patterns.
Drools was created as a rule engine but has expanded to become a business modeling platform through the integration of business rule management, business process management, and complex event processing. It achieves this through modules like Drools Expert (rules), Drools Flow (processes), Drools Fusion (events), and Drools Planner (planning). Drools Guvnor provides a centralized repository for managing knowledge bases. The platform uses a declarative approach to represent business logic and processes through rules, events, and planning constraints.
Java 7, 8 & 9 - Moving the language forwardMario Fusco
The document summarizes new features in Java 7-8 including lambda expressions, switch on strings, try-with-resources, and the fork/join framework. Java 8 will focus on lambda expressions to provide functional programming capabilities and default methods to allow interfaces to have default implementations without breaking existing implementations. Java 9 may include additional modularization support.
Hammurabi is an internal domain-specific language (DSL) for rule-based programming implemented in Scala. It allows domain experts to write rules in plain Scala code without learning a new language. Rules are evaluated by a rule engine that executes matching rules on a working memory of facts. The DSL aims to be readable, flexible and leverage Scala features like autocompletion. It also supports priorities, selecting objects, and exiting or failing evaluation. The architecture uses actors for concurrent rule evaluation. Future work includes improving performance using RETE algorithm and providing alternative selection methods.
This document summarizes Spring features for building loosely coupled, maintainable applications. It discusses how Spring promotes loose coupling through dependency injection and application events. It also describes how to implement workflows with jBPM and manage transactions declaratively in Spring.
Lambdaj is an internal DSL that allows manipulating collections without loops. It provides static methods to filter, sort, extract, and otherwise operate on collections. By treating collections as single objects and allowing method references, lambdaj can concisely represent operations that would otherwise require loops. While lambdaj is generally 4-6 times slower than iterative versions, it improves readability of collection operations.
This document discusses concurrency, scalability, and fault tolerance using actors and software transactional memory (STM) in Akka. It describes how actors provide message-passing concurrency by isolating processes and avoiding shared state. Actors allow easy reasoning about concurrency by preventing issues like race conditions and deadlocks. The document also covers how Akka implements actors, typed actors, remote actors, supervisor hierarchies for fault tolerance, and STM for coordinating concurrent changes to shared state transactionally. Combining actors with STM results in "transactors" that allow building distributed, concurrent, and fault-tolerant applications.
Scala - where objects and functions meetMario Fusco
The document provides an overview of a two-day training course on Scala that covers topics like object orientation, functional programming, pattern matching, generics, traits, case classes, tuples, collections, concurrency, options and monads. The course aims to show how Scala combines object-oriented and functional programming approaches and provides examples of commonly used Scala features like classes, traits, pattern matching, generics and collections.
How to purchase, license and subscribe to Microsoft Azure_PDF.pdfvictordsane
Microsoft Azure is a cloud platform that empowers businesses with scalable computing, data analytics, artificial intelligence, and cybersecurity capabilities.
Arguably the biggest hurdle for most organizations is understanding how to get started.
Microsoft Azure is a consumption-based cloud service. This means you pay for what you use. Unlike traditional software, Azure resources (e.g., VMs, databases, storage) are billed based on usage time, storage size, data transfer, or resource configurations.
There are three primary Azure purchasing models:
• Pay-As-You-Go (PAYG): Ideal for flexibility. Billed monthly based on actual usage.
• Azure Reserved Instances (RI): Commit to 1- or 3-year terms for predictable workloads. This model offers up to 72% cost savings.
• Enterprise Agreements (EA): Best suited for large organizations needing comprehensive Azure solutions and custom pricing.
Licensing Azure: What You Need to Know
Azure doesn’t follow the traditional “per seat” licensing model. Instead, you pay for:
• Compute Hours (e.g., Virtual Machines)
• Storage Used (e.g., Blob, File, Disk)
• Database Transactions
• Data Transfer (Outbound)
Purchasing and subscribing to Microsoft Azure is more than a transactional step, it’s a strategic move.
Get in touch with our team of licensing experts via [email protected] to further understand the purchasing paths, licensing options, and cost management tools, to optimize your investment.
Build enterprise-ready applications using skills you already have!PhilMeredith3
Process Tempo is a rapid application development (RAD) environment that empowers data teams to create enterprise-ready applications using skills they already have.
With Process Tempo, data teams can craft beautiful, pixel-perfect applications the business will love.
Process Tempo combines features found in business intelligence tools, graphic design tools and workflow solutions - all in a single platform.
Process Tempo works with all major databases such as Databricks, Snowflake, Postgres and MySQL. It also works with leading graph database technologies such as Neo4j, Puppy Graph and Memgraph.
It is the perfect platform to accelerate the delivery of data-driven solutions.
For more information, you can find us at www.processtempo.com
Secure and Simplify IT Management with ManageEngine Endpoint Central.pdfNorthwind Technologies
ManageEngine Endpoint Central (formerly known as Desktop Central) is an all-in-one endpoint management solution designed for managing a diverse and distributed IT environment. It supports Windows, macOS, Linux, iOS, Android, and Chrome OS devices, offering a centralized approach to managing endpoints — whether they’re on-premise, remote, or hybrid.
Explore the professional resume of Pramod Kumar, a skilled iOS developer with extensive experience in Swift, SwiftUI, and mobile app development. This portfolio highlights key projects, technical skills, and achievements in app design and development, showcasing expertise in creating intuitive, high-performance iOS applications. Ideal for recruiters and tech managers seeking a talented iOS engineer for their team.
Rebuilding Cadabra Studio: AI as Our Core FoundationCadabra Studio
Cadabra Studio set out to reconstruct its core processes, driven entirely by AI, across all functions of its software development lifecycle. This journey resulted in remarkable efficiency improvements of 40–80% and reshaped the way teams collaborate. This presentation shares our challenges and lessons learned in becoming an AI-native firm, including overcoming internal resistance and achieving significant project delivery gains. Discover our strategic approach and transformative recommendations to integrate AI not just as a feature, but as a fundamental element of your operational structure. What changes will AI bring to your company?
Shortcomings of EHS Software – And How to Overcome ThemTECH EHS Solution
Shortcomings of EHS Software—and What Overcomes Them
What you'll learn in just 8 slides:
- 🔍 Why most EHS software implementations struggle initially
- 🚧 3 common pitfalls: adoption, workflow disruption, and delayed ROI
- 🛠️ Practical solutions that deliver long-term value
- 🔐 Key features: centralization, security, affordability
- 📈 Why the pros outweigh the cons
Perfect for HSE heads, plant managers, and compliance leads!
#EHS #TECHEHS #WorkplaceSafety #EHSCompliance #EHSManagement #ehssoftware #safetysoftware
How AI Can Improve Media Quality Testing Across Platforms (1).pptxkalichargn70th171
Media platforms, from video streaming to OTT and Smart TV apps, face unprecedented pressure to deliver seamless, high-quality experiences across diverse devices and networks. Ensuring top-notch Quality of Experience (QoE) is critical for user satisfaction and retention.
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdfQuickBooks Training
Are you preparing your budget for the next year, applying for a business credit card or loan, or opening a company bank account? If so, you may find QuickBooks financial statements to be a very useful tool.
These statements offer a brief, well-structured overview of your company’s finances, facilitating goal-setting and money management.
Don’t worry if you’re not knowledgeable about QuickBooks financial statements. These statements are complete reports from QuickBooks that provide an overview of your company’s financial procedures.
They thoroughly view your financial situation by including important features: income, expenses, investments, and disadvantages. QuickBooks financial statements facilitate your financial management and assist you in making wise determinations, regardless of your experience as a business owner.
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATIONmiso_uam
AI-ASSISTED METAMORPHIC TESTING FOR DOMAIN-SPECIFIC MODELLING AND SIMULATION (plenary talk at ANNSIM'2025)
Testing is essential to improve the correctness of software systems. Metamorphic testing (MT) is an approach especially suited when the system under test lacks oracles, or they are expensive to compute. However, building an MT environment for a particular domain (e.g., cloud simulation, automated driving simulation, production system simulation, etc) requires substantial effort.
To alleviate this problem, we propose a model-driven engineering approach to automate the construction of MT environments, which is especially useful to test domain-specific modelling and simulation systems. Starting from a meta-model capturing the domain concepts, and a description of the domain execution environment, our approach produces an MT environment featuring comprehensive support for the MT process. This includes the definition of domain-specific metamorphic relations, their evaluation, detailed reporting of the testing results, and the automated search-based generation of follow-up test cases.
In this talk, I presented the approach, along with ongoing work and perspectives for integrating intelligence assistance based on large language models in the MT process. The work is a joint collaboration with Pablo Gómez-Abajo, Pablo C. Cañizares and Esther Guerra from the miso research group and Alberto Núñez from UCM.
Autoposting.ai Sales Deck - Skyrocket your LinkedIn's ROIUdit Goenka
1billion people scroll, only 1 % post…
That’s your opening to hijack LinkedIn—and Autoposting.ai is the unfair weapon Slideshare readers are hunting for…
LinkedIn drives 80 % of social B2B leads, converts 2× better than every other network, yet 87 % of pros still choke on the content hamster-wheel…
They burn 25 h a month writing beige posts, miss hot trends, then watch rivals scoop the deals…
Enter Autoposting.ai, the first agentic-AI engine built only for LinkedIn domination…
It spies on fresh feed data, cracks trending angles before they peak, and spins voice-perfect thought-leadership that sounds like you—not a robot…
Slides in play:
• 78 % average engagement lift in 90 days…
• 3.2× qualified-lead surge over manual posting…
• 42 % marketing time clawed back, week after week…
Real users report 5-8× ROI inside the first quarter, some crossing $1 M ARR six months faster…
Why does it hit harder than Taplio, Supergrow, generic AI writers?
• Taplio locks key features behind $149+ tiers… Autoposting gives you everything at $29…
• Supergrow churns at 20 % because “everyone” is no-one… Autoposting laser-targets • • LinkedIn’s gold-vein ICPs and keeps them glued…
• ChatGPT needs prompts, edits, scheduling hacks… Autoposting researches, writes, schedules—and optimizes send-time in one sweep…
Need social proof?
G2 reviews scream “game-changer”… Agencies slash content production 80 % and triple client capacity… CXOs snag PR invites and investor DMs after a single week of daily posts… Employee advocates hit 8× reach versus company pages and pump 25 % more SQLs into the funnel…
Feature bullets for the skim-reader:
• Agentic Research Engine—tracks 27+ data points, finds gaps your rivals ignore…
• Real Voice Match—your tone, slang, micro-jokes, intact…
• One-click Multiplatform—echo winning posts to Twitter, Insta, Facebook…
• Team Workspaces—spin up 10 seats without enterprise red tape…
• AI Timing—drops content when your buyers actually scroll, boosting first-hour velocity by up to 4×…
Risk? Zero…
Free 7-day trial, 90-day results guarantee—hit 300 % ROI or walk away… but the clock is ticking while competitors scoop your feed…
So here’s the ask:
Swipe down, smash the “Download” or “Try Now” button, and let Autoposting.ai turn Slideshare insights into pipeline—before today’s trending topic vanishes…
The window is open… How loud do you want your LinkedIn megaphone?
Online Queue Management System for Public Service Offices [Focused on Municip...Rishab Acharya
This report documents the design and development of an Online Queue Management System tailored specifically for municipal offices in Nepal. Municipal offices, as critical providers of essential public services, face challenges including overcrowded queues, long waiting times, and inefficient service delivery, causing inconvenience to citizens and pressure on municipal staff. The proposed digital platform allows citizens to book queue tokens online for various physical services, facilitating efficient queue management and real-time wait time updates. Beyond queue management, the system includes modules to oversee non-physical developmental programs, such as educational and social welfare initiatives, enabling better participation and progress monitoring. Furthermore, it incorporates a module for monitoring infrastructure development projects, promoting transparency and allowing citizens to report issues and track progress. The system development follows established software engineering methodologies, including requirement analysis, UML-based system design, and iterative testing. Emphasis has been placed on user-friendliness, security, and scalability to meet the diverse needs of municipal offices across Nepal. Implementation of this integrated digital platform will enhance service efficiency, increase transparency, and improve citizen satisfaction, thereby supporting the modernization and digital transformation of public service delivery in Nepal.
AI Alternative - Discover the best AI tools and their alternativesAI Alternative
AIAlternative.co is a comprehensive directory designed to help users discover, compare, and evaluate AI tools across various domains. Its primary goal is to assist individuals and businesses in finding the most suitable AI solutions tailored to their specific needs.
Key Features
- Curated AI Tool Listings: The platform offers detailed information on a wide range of AI tools, including their functionalities, use cases, and alternatives. This allows users to make informed decisions based on their requirements.
- Alternative Suggestions: For each listed AI tool, aialternative.co provides suggestions for similar or alternative tools, facilitating easier comparison and selection.
- Regular Updates: The directory is consistently updated to include the latest AI innovations, ensuring users have access to the most current tools available in the market.
Browse All Tools here: https://aialternative.co/
Scalefusion Remote Access for Apple DevicesScalefusion
🔌Tried restarting.
🔁Then updating.
🔎Then Googled a fix.
And then it crashed.
Guess who has to fix it? You. And who’ll help you? - Scalefusion.
Scalefusion steps in with real-time access, not just remote hope. Support for Apple devices that support you (and them) to do more.
For more: https://scalefusion.com/remote-access-software-mac
https://scalefusion.com/es/remote-access-software-mac
https://scalefusion.com/fr/remote-access-software-mac
https://scalefusion.com/pt-br/remote-access-software-mac
https://scalefusion.com/nl/remote-access-software-mac
https://scalefusion.com/de/remote-access-software-mac
https://scalefusion.com/ru/remote-access-software-mac
In today’s workplace, staying connected is more important than ever. Whether teams are remote, hybrid, or back in the office, communication and collaboration are at the heart of getting things done. But here’s the truth — outdated intranets just don’t cut it anymore.
Boost Student Engagement with Smart Attendance Software for SchoolsVisitu
Boosting student engagement is crucial for educational success, and smart attendance software is a powerful tool in achieving that goal. Read the doc to know more.
The rise of e-commerce has redefined how retailers operate—and reconciliation...Prachi Desai
As payment flows grow more fragmented, the complexity of reconciliation and revenue recognition increases. The result? Mounting operational costs, silent revenue leakages, and avoidable financial risk.
Spot the inefficiencies. Automate what’s slowing you down.
https://www.taxilla.com/ecommerce-reconciliation
2. Lazy Evaluation
Lazy evaluation (or call-by-name) is an evaluation
strategy which delays the evaluation of an expression
until its value is needed
I know what to do.
Wake me up when
you really need it
3. Strictness vs. Laziness
Strictness is a property of functions (or methods in Java).
A strict function always evaluates its arguments as soon
as they’re passed to it.
Conversely a lazy function may choose not to evaluate one
or more of its arguments and in general it will evaluate
them only when they’re actually needed.
To recap,
strictness is about doing things,
laziness is about noting things to do.
4. Java is a strict language ...
… with some notable (and unavoidable) exceptions
✔
Boolean operators || and &&
✔
Ternary operator ? :
✔
if ... else
✔
for/while loops
✔
Java 8 streams
Q: Can exist a totally strict language?
5. Java is a strict language ...
… with some notable (and unavoidable) exceptions
✔
Boolean operators || and &&
✔
Ternary operator ? :
✔
if ... else
✔
for/while loops
✔
Java 8 streams
Q: Can exist a totally strict language?
A: It’s hard if not impossible to imagine how it could work
boolean isAdult = person != null && person.getAge() >= 18;
6. Turning Java into a lazy language
<T> T ternary(boolean pred, T first, T second) {
if (pred) {
return first;
} else {
return second;
}
}
String val1() {
return "first";
}
String val2() {
return "second";
}
String result1 = bool ? val1() : val2();
String result2 = ternary(bool, val1(), val2());
8. A simple practical example: logging
// pre-Java 8 style optimization
if (logger.isTraceEnabled()) {
logger.trace("Some long-running operation returned {}",
expensiveOperation());
}
9. A simple practical example: logging
// pre-Java 8 style optimization
if (logger.isTraceEnabled()) {
logger.trace("Some long-running operation returned {}",
expensiveOperation());
}
// Java 8 style optimization using laziness
logger.trace("Some long-running operation returned {}",
() -> expensiveOperation());
* from Apache Log4J 2 docs
no need to explicitly check the log level:
the lambda expression is not evaluated
if the TRACE level is not enabled *
10. Laziness: the ultimate performance
optimization technique
Performance optimization pro tip:
before trying to inline/optimize/parallelize a piece of code,
ask yourself if you could avoid to run it at all.
Laziness is
probably the
only form of
performance
optimization
which is (almost)
never premature
There is nothing so useless as doing efficiently
something that should not be done at all
11. The case of Java 8 Streams
IntStream.iterate( 1, i -> i+1 )
.map( i -> i * 2 )
.filter( i -> i > 5 )
.findFirst();
12. The case of Java 8 Streams
IntStream.iterate( 1, i -> i+1 )
.map( i -> i * 2 )
.filter( i -> i > 5 )
.findFirst();
Thank to laziness the Stream
can be potentially infinite
13. The case of Java 8 Streams
IntStream.iterate( 1, i -> i+1 )
.map( i -> i * 2 )
.filter( i -> i > 5 )
.findFirst();
Thank to laziness the Stream
can be potentially infinite
Intermediate operations are lazy:
they don’t perform any action until
a terminal operation is reached
14. The case of Java 8 Streams
IntStream.iterate( 1, i -> i+1 )
.map( i -> i * 2 )
.filter( i -> i > 5 )
.findFirst();
Thank to laziness the Stream
can be potentially infinite
Intermediate operations are lazy:
they don’t perform any action until
a terminal operation is reached
Only the terminal operation
triggers the pipeline of
computations
A Stream is not a data structure.
It is the lazy specification of a how
to manipulate a set of data.
15. Things you can’t do without laziness
There are several algorithms that can’t be
(reasonably) implemented without laziness.
For example let’s consider the following:
1. Take the list of positive integers.
2. Filter the primes.
3. Return the list of the first ten results.
16. Wait! I can achieve the same with a
strict algorithm
Yes, but how?
1. Take the first integer.
2. Check whether it’s a prime.
3. If it is, store it in a list.
4. Check whether the list has ten elements.
5. If it has ten elements, return it as the result.
6. If not, increment the integer by 1.
7. Go to line 2.
17. Wait! I can achieve the same with a
strict algorithm
Yes, but how?
1. Take the first integer.
2. Check whether it’s a prime.
3. If it is, store it in a list.
4. Check whether the list has ten elements.
5. If it has ten elements, return it as the result.
6. If not, increment the integer by 1.
7. Go to line 2.
Sure, doable …
but what a mess!
18. Laziness lets us separate the description of an
expression from the evaluation of that expression
Laziness is an enabler for separation of concerns
19. List<String> errors =
Files.lines(Paths.get(fileName))
.filter(l -> l.startsWith("ERROR"))
.limit(40)
.collect(toList());
Separation of Concerns
List<String> errors = new ArrayList<>();
int errorCount = 0;
File file = new File(fileName);
String line = file.readLine();
while (errorCount < 40 && line != null) {
if (line.startsWith("ERROR")) {
errors.add(line);
errorCount++;
}
line = file.readLine();
}
20. Cool! Now I know:
I will use a Stream
also for prime
numbers
21. Cool! Now I know:
I will use a Stream
also for prime
numbers
Let’s give this a try ...
22. Creating a Stream of prime numbers
public IntStream primes(int n) {
return IntStream.iterate(2, i -> i + 1)
.filter(this::isPrime)
.limit(n);
}
public boolean isPrime(int candidate) {
return IntStream.rangeClosed(2, (int)Math.sqrt(candidate))
.noneMatch(i -> candidate % i == 0);
}
23. Creating a Stream of prime numbers
public IntStream primes(int n) {
return IntStream.iterate(2, i -> i + 1)
.filter(this::isPrime)
.limit(n);
}
public boolean isPrime(int candidate) {
return IntStream.rangeClosed(2, (int)Math.sqrt(candidate))
.noneMatch(i -> candidate % i == 0);
}
It iterates through every number every time to see if it can be
exactly divided by a candidate number, but it would be enough
to only test numbers that have been already classified as prime
Inefficient
24. Recursively creating a Stream of primes
static Intstream numbers() {
return IntStream.iterate(2, n -> n + 1);
}
static int head(IntStream numbers) {
return numbers.findFirst().getAsInt();
}
static IntStream tail(IntStream numbers) {
return numbers.skip(1);
}
static IntStream primes(IntStream numbers) {
int head = head(numbers());
return IntStream.concat(
IntStream.of(head),
primes(tail(numbers).filter(n -> n % head != 0))
);
}
Cannot invoke 2
terminal operations
on the same Streams
Problems?
No lazy evaluation
in Java leads to an
endless recursion
25. Lazy evaluation in Scala
def numbers(n: Int): Stream[Int] = n #:: numbers(n+1)
def primes(numbers: Stream[Int]): Stream[Int] =
numbers.head #::
primes(numbers.tail filter (n -> n % numbers.head != 0))
lazy concatenation
In Scala the #:: method (lazy concatenation)
returns immediately and the elements are
evaluated only when needed
26. interface HeadTailList<T> {
T head();
HeadTailList<T> tail();
boolean isEmpty();
HeadTailList<T> filter(Predicate<T> p);
}
Implementing a lazy list in Java
class LazyList<T> implements HeadTailList<T> {
private final T head;
private final Supplier<HeadTailList<T>> tail;
public LazyList(T head,
Supplier<HeadTailList<T>> tail) {
this.head = head;
this.tail = tail;
}
public T head() { return head; }
public HeadTailList<T> tail() { return tail.get(); }
public boolean isEmpty() { return false; }
}
27. … and its lazy filter
class LazyList<T> implements HeadTailList<T> { ...
public HeadTailList<T> filter(Predicate<T> p) {
return isEmpty() ?
this :
p.test(head()) ?
new LazyList<>(head(), () -> tail().filter(p)) :
tail().filter(p);
}
} 2
3 4
5
6
7
8
9
2
3
5
7
28. Back to generating primes
static HeadTailList<Integer> primes(HeadTailList<Integer> numbers) {
return new LazyList<>(
numbers.head(),
() -> primes(numbers.tail()
.filter(n -> n % numbers.head() != 0)));
}
static LazyList<Integer> from(int n) {
return new LazyList<Integer>(n, () -> from(n+1));
}
29. Back to generating primes
static HeadTailList<Integer> primes(HeadTailList<Integer> numbers) {
return new LazyList<>(
numbers.head(),
() -> primes(numbers.tail()
.filter(n -> n % numbers.head() != 0)));
}
static LazyList<Integer> from(int n) {
return new LazyList<Integer>(n, () -> from(n+1));
}
LazyList<Integer> numbers = from(2);
int two = primes(numbers).head();
int three = primes(numbers).tail().head();
int five = primes(numbers).tail().tail().head();
30. LazyList of primes under the hood
from(2) → 2 () -> from(3)
2 () -> primes( from(3).filter(2) )primes(from(2)) →
35. Iteration vs. Recursion
External Iteration
public int sumAll(int n) {
int result = 0;
for (int i = 0; i <= n; i++) {
result += i;
}
return result;
}
Internal Iteration
public static int sumAll(int n) {
return IntStream.rangeClosed(0, n).sum();
}
36. Iteration vs. Recursion
External Iteration
public int sumAll(int n) {
int result = 0;
for (int i = 0; i <= n; i++) {
result += i;
}
return result;
}
Recursion
public int sumAll(int n) {
return n == 0 ? 0 : n + sumAll(n - 1);
}
Internal Iteration
public static int sumAll(int n) {
return IntStream.rangeClosed(0, n).sum();
}
37. public class PalindromePredicate implements Predicate<String> {
@Override public boolean test(String s) {
return isPalindrome(s, 0, s.length()-1);
}
private boolean isPalindrome(String s, int start, int end) {
while (start < end && !isLetter(s.charAt(start))) start++;
while (start < end && !isLetter(s.charAt(end))) end--;
if (start >= end) return true;
if (toLowerCase(s.charAt(start)) !=
toLowerCase(s.charAt(end))) return false;
return isPalindrome(s, start+1, end-1);
}
}
Another Recursive Example
Tail Rescursive Call
38. What's the problem?
List<String> sentences = asList( "Dammit, I’m mad!",
"Rise to vote, sir!",
"Never odd or even",
"Never odd and even",
"Was it a car or a cat I saw?",
"Was it a car or a dog I saw?",
VERY_LONG_PALINDROME );
sentences.stream()
.filter(new PalindromePredicate())
.forEach(System.out::println);
39. What's the problem?
List<String> sentences = asList( "Dammit, I’m mad!",
"Rise to vote, sir!",
"Never odd or even",
"Never odd and even",
"Was it a car or a cat I saw?",
"Was it a car or a dog I saw?",
VERY_LONG_PALINDROME );
sentences.stream()
.filter(new PalindromePredicate())
.forEach(System.out::println);
Exception in thread "main" java.lang.StackOverflowError
at java.lang.Character.getType(Character.java:6924)
at java.lang.Character.isLetter(Character.java:5798)
at java.lang.Character.isLetter(Character.java:5761)
at org.javaz.trampoline.PalindromePredicate.isPalindrome(PalindromePredicate.java:17)
at org.javaz.trampoline.PalindromePredicate.isPalindrome(PalindromePredicate.java:21)
at org.javaz.trampoline.PalindromePredicate.isPalindrome(PalindromePredicate.java:21)
at org.javaz.trampoline.PalindromePredicate.isPalindrome(PalindromePredicate.java:21)
……..
40. Tail Call Optimization
int func_a(int data) {
data = do_this(data);
return do_that(data);
} ... | executing inside func_a()
push EIP | push current instruction pointer on stack
push data | push variable 'data' on the stack
jmp do_this | call do_this() by jumping to its address
... | executing inside do_this()
push EIP | push current instruction pointer on stack
push data | push variable 'data' on the stack
jmp do_that | call do_that() by jumping to its address
... | executing inside do_that()
pop data | prepare to return value of 'data'
pop EIP | return to do_this()
pop data | prepare to return value of 'data'
pop EIP | return to func_a()
pop data | prepare to return value of 'data'
pop EIP | return to func_a() caller
...
caller
41. Tail Call Optimization
int func_a(int data) {
data = do_this(data);
return do_that(data);
} ... | executing inside func_a()
push EIP | push current instruction pointer on stack
push data | push variable 'data' on the stack
jmp do_this | call do_this() by jumping to its address
... | executing inside do_this()
push EIP | push current instruction pointer on stack
push data | push variable 'data' on the stack
jmp do_that | call do_that() by jumping to its address
... | executing inside do_that()
pop data | prepare to return value of 'data'
pop EIP | return to do_this()
pop data | prepare to return value of 'data'
pop EIP | return to func_a()
pop data | prepare to return value of 'data'
pop EIP | return to func_a() caller
...
caller
avoid putting
instruction
on stack
42. from Recursion to Tail Recursion
Recursion
public int sumAll(int n) {
return n == 0 ?
0 :
n + sumAll(n - 1);
}
43. from Recursion to Tail Recursion
Recursion
public int sumAll(int n) {
return n == 0 ?
0 :
n + sumAll(n - 1);
}
Tail Recursion
public int sumAll(int n) {
return sumAll(n, 0);
}
private int sumAll(int n, int acc) {
return n == 0 ?
acc :
sumAll(n – 1, acc + n);
}
44. Tail Recursion in Scala
def isPalindrome(s: String): Boolean = isPalindrome(s, 0, s.length-1)
@tailrec
def isPalindrome(s: String, start: Int, end: Int): Boolean = {
val pos1 = nextLetter(s, start, end)
val pos2 = prevLetter(s, start, end)
if (pos1 >= pos2) return true
if (toLowerCase(s.charAt(pos1)) !=
toLowerCase(s.charAt(pos2))) return false
isPalindrome(s, pos1+1, pos2-1)
}
@tailrec def nextLetter(s: String, start: Int, end: Int): Int =
if (start > end || isLetter(s.charAt(start))) start
else nextLetter(s, start+1, end)
@tailrec def prevLetter(s: String, start: Int, end: Int): Int =
if (start > end || isLetter(s.charAt(end))) end
else prevLetter(s, start, end-1)
45. Tail Recursion in Java?
Scala (and many other functional languages) automatically
perform tail call optimization at compile time
@tailrec annotation ensures the compiler will optimize a tail
recursive function (i.e. you will get a compilation failure if you
use it on a function that is not really tail recursive)
Java compiler doesn't perform any tail call optimization (and
very likely won't do it in a near future)
How can we overcome this limitation and
have StackOverflowError-free functions also
in Java tail recursive methods?
46. Trampolines to the rescue
A trampoline is an iteration applying a list of functions.
Each function returns the next function for the loop to run.
Func1
return
apply
Func2
return
apply
Func3
return
apply
FuncN
apply
…
result
return
47. Implementing the TailCall …
@FunctionalInterface
public interface TailCall<T> extends Supplier<TailCall<T>> {
default boolean isComplete() { return false; }
default T result() { throw new UnsupportedOperationException(); }
default T invoke() {
return Stream.iterate(this, TailCall::get)
.filter(TailCall::isComplete)
.findFirst()
.get()
.result();
}
static <T> TailCall<T> done(T result) {
return new TerminalCall<T>(result);
}
}
48. … and the terminal TailCall
public class TerminalCall<T> implements TailCall<T> {
private final T result;
public TerminalCall( T result ) {
this.result = result;
}
@Override
public boolean isComplete() { return true; }
@Override
public T result() { return result; }
@Override
public TailCall<T> get() {
throw new UnsupportedOperationException();
}
}
49. Using the Trampoline
public class PalindromePredicate implements Predicate<String> {
@Override public boolean test(String s) {
return isPalindrome(s, 0, s.length()-1).invoke();
}
private TailCall<Boolean> isPalindrome(String s, int start,
int end) {
while (start < end && !isLetter(s.charAt(start))) start++;
while (end > start && !isLetter(s.charAt(end))) end--;
if (start >= end) return done(true);
if (toLowerCase(s.charAt(start)) !=
toLowerCase(s.charAt(end))) return done(false);
int newStart = start + 1;
int newEnd = end - 1;
return () -> isPalindrome(s, newStart, newEnd);
}
}
50. What else laziness can do for us?
Avoiding eager dependency injection by
lazily providing arguments to
computation only when they are needed
i.e.
Introducing the Reader Monad
51. What’s wrong with annotation-
based dependency injection?
➢ Eager in nature
➢ “new” keyword is forbidden
➢ All-your-beans-belong-to-us
syndrome
➢ Complicated objects lifecycle
➢ Depending on scope may
not work well with threads
➢ Hard to debug if something
goes wrong
➢ Easy to abuse leading to
broken encapsulation
53. Introducing the Reader monad ...
public class Reader<R, A> {
private final Function<R, A> exec;
public Reader( Function<R, A> exec ) {
this.exec = exec;
}
public <B> Reader<R, B> map(Function<A, B> f) {
return new Reader<>( exec.andThen(f) );
}
public <B> Reader<R, B> flatMap(Function<A, Reader<R, B>> f) {
return new Reader<>( r -> exec.andThen(f).apply(r).apply(r) );
}
public A apply(R r) {
return exec.apply( r );
}
}
The reader monad provides an environment to
wrap an abstract computation without evaluating it
54. The Reader Monad
The Reader monad makes
a lazy computation
explicit
in the type system, while
hiding
the logic to apply it
In other words the reader monad
allows us to treat functions as
values with a context
We can act as if we already know
what the functions will return.
55. @FunctionalInterface
public interface Logger extends Consumer<String> { }
public class Account {
private Logger logger;
private String owner;
private double balance;
public Account open( String owner ) {
this.owner = owner;
logger.accept( "Account opened by " + owner );
return this;
}
public Account credit( double value ) {
balance += value;
logger.accept( "Credited " + value + " to " + owner );
return this;
}
public Account debit( double value ) {
balance -= value;
logger.accept( "Debited " + value + " to " + owner );
return this;
}
public double getBalance() { return balance; }
public void setLogger( Logger logger ) { this.logger = logger; }
}
Usually injected
56. Account account = new Account();
account.open( "Alice" )
.credit( 200.0 )
.credit( 300.0 )
.debit( 400.0 );
The joys of dependency injection
57. Account account = new Account();
account.open( "Alice" )
.credit( 200.0 )
.credit( 300.0 )
.debit( 400.0 );
Throws NPE if for some
reason the logger
couldn’t be injected
The joys of dependency injection :(
You should never use “new”
58. public static <R, A> Reader<R, A> lift( A obj,
BiConsumer<A, R> injector ) {
return new Reader<>( r -> {
injector.accept( obj, r );
return obj;
} );
}
Lazy injection with the reader monad
59. public static <R, A> Reader<R, A> lift( A obj,
BiConsumer<A, R> injector ) {
return new Reader<>( r -> {
injector.accept( obj, r );
return obj;
} );
}
Lazy injection with the reader monad
Account account = new Account();
Reader<Logger, Account> reader =
lift(account, Account::setLogger )
.map( a -> a.open( "Alice" ) )
.map( a -> a.credit( 200.0 ) )
.map( a -> a.credit( 300.0 ) )
.map( a -> a.debit( 400.0 ) );
reader.apply( System.out::println );
System.out.println(account + " has balance " + account.getBalance());
60. public static <R, A> Reader<R, A> lift( A obj,
BiConsumer<A, R> injector ) {
return new Reader<>( r -> {
injector.accept( obj, r );
return obj;
} );
}
Lazy injection with the reader monad
Account account = new Account();
Reader<Logger, Account> reader =
lift(account, Account::setLogger )
.map( a -> a.open( "Alice" ) )
.map( a -> a.credit( 200.0 ) )
.map( a -> a.credit( 300.0 ) )
.map( a -> a.debit( 400.0 ) );
reader.apply( System.out::println );
System.out.println(account + " has balance " + account.getBalance());
62. Function based injection
Account account = new Account();
Function<Logger, Account> inject = l -> {
account.setLogger( l );
return account;
};
Function<Logger, Account> f = inject
.andThen( a -> a.open( "Alice" ) )
.andThen( a -> a.credit( 200.0 ) )
.andThen( a -> a.credit( 300.0 ) )
.andThen( a -> a.debit( 400.0 ) );
f.apply( System.out::println );
System.out.println(account + " has balance " + account.getBalance());
The reader monad provides a more
structured and powerful approach.
In this simple case a simple function composition
is enough to achieve the same result.
63. public class Account { ...
public MoneyTransfer tranfer( double value ) {
return new MoneyTransfer( this, value );
}
}
public class MoneyTransfer {
private Logger logger;
private final Account account;
private final double amount;
public MoneyTransfer( Account account, double amount ) {
this.account = account;
this.amount = amount;
}
public void setLogger( Logger logger ) { this.logger = logger; }
public MoneyTransfer execute() {
account.debit( amount );
logger.accept( "Transferred " + amount + " from " + account );
return this;
}
}
Injecting into multiple objects
64. Injecting into multiple objects
Account account = new Account();
Reader<Logger, MoneyTransfer> reader =
lift(account, Account::setLogger )
.map( a -> a.open( "Alice" ) )
.map( a -> a.credit( 300.0 ) )
.flatMap( a -> lift( a.tranfer( 200.0 ), MoneyTransfer::setLogger ) )
.map( MoneyTransfer::execute );
reader.apply( System.out::println );
System.out.println(account + " has balance " + account.getBalance());
65. Injecting into multiple objects
Account account = new Account();
Reader<Logger, MoneyTransfer> reader =
lift(account, Account::setLogger )
.map( a -> a.open( "Alice" ) )
.map( a -> a.credit( 300.0 ) )
.flatMap( a -> lift( a.tranfer( 200.0 ), MoneyTransfer::setLogger ) )
.map( MoneyTransfer::execute );
reader.apply( System.out::println );
System.out.println(account + " has balance " + account.getBalance());