This document discusses domain modeling in a functional world based on the speaker's real life experiences. The speaker covers topics like immutability and algebraic data types, updating domain models functionally using lenses, type classes for domain modeling, and managing states functionally. The speaker advocates for isolating pure domain logic from side effects to make the logic easier to test, reason about, and parallelize. Functional composition is emphasized as a way to build complex abstractions from simpler ones.
Functional Domain Modeling - The ZIO 2 WayDebasish Ghosh
Principled way to design and implement functional domain models using some of the patterns of domain driven design. DDD, as the name suggests, is focused towards the domain model and the patterns of architecture that it encourages are also based on how we think of interactions amongst the basic abstractions of the domain. Of course the primary goal of the talk is to discuss how Scala and Zio 2 can be a potent combination in realizing the implementation of such models. This is not a talk on FP, the focus will be on how to structure and modularise an application based on some of the patterns of DDD.
Algebraic Thinking for Evolution of Pure Functional Domain ModelsDebasish Ghosh
The focus of the talk is to emphasize the importance of algebraic thinking when designing pure functional domain models. The talk begins with the definition of an algebra as consisting of a carrier type, a set of operations/functions and a set of laws on those operations. Using examples from the standard library, the talk shows how thinking of abstractions in terms of its algebra is more intuitive than discussing its operational semantics. The talk also discusses the virtues of parametricity and compositionality in designing proper algebras.
Algebras are compositional and help build larger algebras out of smaller ones. We start with base level types available in standard libraries and compose larger programs out of them. We take a real life use case for a domain model and illustrate how we can define the entire model using the power of algebraic composition of the various types. We talk about how to model side-effects as pure abstractions using algebraic effects. At no point we will talk about implementations.
At the end of the talk we will have a working model built completely out of the underlying algebra of the domain language.
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
Scala Intro training @ Lohika, Odessa, UA.
This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.
Functional Domain Modeling - The ZIO 2 WayDebasish Ghosh
Principled way to design and implement functional domain models using some of the patterns of domain driven design. DDD, as the name suggests, is focused towards the domain model and the patterns of architecture that it encourages are also based on how we think of interactions amongst the basic abstractions of the domain. Of course the primary goal of the talk is to discuss how Scala and Zio 2 can be a potent combination in realizing the implementation of such models. This is not a talk on FP, the focus will be on how to structure and modularise an application based on some of the patterns of DDD.
Algebraic Thinking for Evolution of Pure Functional Domain ModelsDebasish Ghosh
The focus of the talk is to emphasize the importance of algebraic thinking when designing pure functional domain models. The talk begins with the definition of an algebra as consisting of a carrier type, a set of operations/functions and a set of laws on those operations. Using examples from the standard library, the talk shows how thinking of abstractions in terms of its algebra is more intuitive than discussing its operational semantics. The talk also discusses the virtues of parametricity and compositionality in designing proper algebras.
Algebras are compositional and help build larger algebras out of smaller ones. We start with base level types available in standard libraries and compose larger programs out of them. We take a real life use case for a domain model and illustrate how we can define the entire model using the power of algebraic composition of the various types. We talk about how to model side-effects as pure abstractions using algebraic effects. At no point we will talk about implementations.
At the end of the talk we will have a working model built completely out of the underlying algebra of the domain language.
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
Scala Intro training @ Lohika, Odessa, UA.
This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.
Http4s, Doobie and Circe: The Functional Web StackGaryCoady
Http4s, Doobie and Circe together form a nice platform for building web services. This presentations provides an introduction to using them to build your own service.
Functional Programming Patterns (NDC London 2014)Scott Wlaschin
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1Philip Schwarz
slides can look grainy and/or out of focus when seen on slideshare - download for flawless quality - Based on Scott Wlaschin’s great book 'Domain Modeling Made Functional' and on Martin Odersky's talk 'A Tour of Scala 3'.
(Video of these slides here http://fsharpforfunandprofit.com/rop)
(My response to "this is just Either" here: http://fsharpforfunandprofit.com/rop/#monads)
Many examples in functional programming assume that you are always on the "happy path". But to create a robust real world application you must deal with validation, logging, network and service errors, and other annoyances.
So, how do you handle all this in a clean functional way? This talk will provide a brief introduction to this topic, using a fun and easy-to-understand railway analogy.
Left and Right Folds- Comparison of a mathematical definition and a programm...Philip Schwarz
We compare typical definitions of the left and right fold functions, with their mathematical definitions in Sergei Winitzki’s upcoming book: The Science of Functional Programming.
Errata:
Slide 13: "The way 𝑓𝑜𝑙𝑑𝑙 does it is by associating to the right" - should, of course ,end in "to the left".
Design functional solutions in Java, a practical exampleMarian Wamsiedel
Starting with a simple programming task I present here some solutions based on functional programming and a standard object oriented one.
The code samples are written in Java. A github repository contains the complete code implementation.
‘go-to’ general-purpose sequential collections -from Java To ScalaPhilip Schwarz
The simple idea of this slide deck is that it collects in a single place quite a bit of information that can be used to gain a basic understanding of some key differences between the ’goto’ sequential collections of Java and Scala.
Errata:
* the twitter handle of Daniel Westheide is @kaffeecoder and not @cafeecoder
* on slide 35, the numbers 215, 220, 225 and 230, should be 2^15, 2^20, 2^25 and 2^30 respectively
* on slide 54, the bottom left node should be green rather than black
Point free or die - tacit programming in Haskell and beyondPhilip Schwarz
I really liked Amar Shah's talk on point-free style as a tool for producing tacit code which communicates better because it is quiet and so easier to understand. https://www.youtube.com/watch?v=seVSlKazsNk
This slide deck is my effort to capture the content of the talk in a way that can aid its consumption, digestion and retention.
Download for better quality.
Tagless Final Encoding - Algebras and Interpreters and also ProgramsPhilip Schwarz
Tagless Final Encoding - Algebras and Interpreters and also Programs - An introduction, through the work of Gabriel Volpe.
Slide deck home: http://fpilluminated.com/assets/tagless-final-encoding-algebras-interpreters-and-programs.html
Let's make a contract: the art of designing a Java APIMario Fusco
An API is what developers use to achieve some task. More precisely it establishes a contract between them and the designers of the software exposing its services through that API. In this sense we're all API designers: our software doesn't work in isolation, but becomes useful only when it interacts with other software written by other developers. When writing software we're not only consumers, but also providers of one or more API and that's why every developer should know the features of a good API. During this presentation we will go through real-world examples, also taken from the standard Java API, of good and bad API and comment them in order to show the dos and don'ts of API design. More in general we will discuss the characteristics of an easy and pleasant to use API, like consistency, discoverability and understandability, together with some basic concepts like the principle of least astonishment, and find out how to achieve them.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Philip Schwarz
(download for perfect quality) - See how recursive functions and structural induction relate to recursive datatypes.
Follow along as the fold abstraction is introduced and explained.
Watch as folding is used to simplify the definition of recursive functions over recursive datatypes
Part 1 - through the work of Richard Bird and Graham Hutton.
This version corrects the following issues:
slide 7, 11 fib(0) is 0,rather than 1
slide 23: was supposed to be followed by 2-3 slides recapitulating definitions of factorial and fibonacci with and without foldr, plus translation to scala
slide 36: concat not invoked in concat example
slides 48 and 49: unwanted 'm' in definition of sum
throughout: a couple of typographical errors
throughout: several aesthetic imperfections (wrong font, wrong font colour)
Domain Driven Design with the F# type System -- NDC London 2013Scott Wlaschin
(Video of these slides here http://fsharpforfunandprofit.com/ddd)
Statically typed functional programming languages like F# encourage a very different way of thinking about types. The type system is your friend, not an annoyance, and can be used in many ways that might not be familiar to OO programmers.
Types can be used to represent the domain in a fine-grained, self documenting way. And in many cases, types can even be used to encode business rules so that you literally cannot create incorrect code. You can then use the static type checking almost as an instant unit test — making sure that your code is correct at compile time.
In this talk, we'll look at some of the ways you can use types as part of a domain driven design process, with some simple real world examples in F#. No jargon, no maths, and no prior F# experience necessary.
Code, links to video, etc., at http://fsharpforfunandprofit.com/ddd
For more on DDD and F# see:
http://fsharpforfunandprofit.com/ddd/
http://tomasp.net/blog/type-first-development.aspx/
http://gorodinski.com/blog/2013/02/17/domain-driven-design-with-fsharp-and-eventstore/
The lazy programmer's guide to writing thousands of testsScott Wlaschin
We are all familiar with example-based testing, as typified by TDD and BDD, where each test is hand-crafted.
But there's another approach to writing tests. In the "property-based testing" approach, a single test is run hundreds of times with randomly generated inputs. Property-based testing is a great way to find edge cases, and also helps you to understand and document the behavior of your code under all conditions.
This talk will introduce property-based testing, show you how it works, and demonstrate why you should consider adding this powerful technique to your toolbelt.
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.
An overview of functional programming. You can do functional programming in any language, it’s just that some languages push you toward this style. There are many styles of programming, depending on the dimension you look at and the features available in the language: Imperative vs Functional, Compiled vs Scripting, Static vs Dynamic, Implicit vs Explicit type conversion, Managed vs Unmanaged (memory). We'll talk about these concepts.
Github: https://github.com/ijcd
Twitter: @ijcd
San Francisco, California
Http4s, Doobie and Circe: The Functional Web StackGaryCoady
Http4s, Doobie and Circe together form a nice platform for building web services. This presentations provides an introduction to using them to build your own service.
Functional Programming Patterns (NDC London 2014)Scott Wlaschin
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1Philip Schwarz
slides can look grainy and/or out of focus when seen on slideshare - download for flawless quality - Based on Scott Wlaschin’s great book 'Domain Modeling Made Functional' and on Martin Odersky's talk 'A Tour of Scala 3'.
(Video of these slides here http://fsharpforfunandprofit.com/rop)
(My response to "this is just Either" here: http://fsharpforfunandprofit.com/rop/#monads)
Many examples in functional programming assume that you are always on the "happy path". But to create a robust real world application you must deal with validation, logging, network and service errors, and other annoyances.
So, how do you handle all this in a clean functional way? This talk will provide a brief introduction to this topic, using a fun and easy-to-understand railway analogy.
Left and Right Folds- Comparison of a mathematical definition and a programm...Philip Schwarz
We compare typical definitions of the left and right fold functions, with their mathematical definitions in Sergei Winitzki’s upcoming book: The Science of Functional Programming.
Errata:
Slide 13: "The way 𝑓𝑜𝑙𝑑𝑙 does it is by associating to the right" - should, of course ,end in "to the left".
Design functional solutions in Java, a practical exampleMarian Wamsiedel
Starting with a simple programming task I present here some solutions based on functional programming and a standard object oriented one.
The code samples are written in Java. A github repository contains the complete code implementation.
‘go-to’ general-purpose sequential collections -from Java To ScalaPhilip Schwarz
The simple idea of this slide deck is that it collects in a single place quite a bit of information that can be used to gain a basic understanding of some key differences between the ’goto’ sequential collections of Java and Scala.
Errata:
* the twitter handle of Daniel Westheide is @kaffeecoder and not @cafeecoder
* on slide 35, the numbers 215, 220, 225 and 230, should be 2^15, 2^20, 2^25 and 2^30 respectively
* on slide 54, the bottom left node should be green rather than black
Point free or die - tacit programming in Haskell and beyondPhilip Schwarz
I really liked Amar Shah's talk on point-free style as a tool for producing tacit code which communicates better because it is quiet and so easier to understand. https://www.youtube.com/watch?v=seVSlKazsNk
This slide deck is my effort to capture the content of the talk in a way that can aid its consumption, digestion and retention.
Download for better quality.
Tagless Final Encoding - Algebras and Interpreters and also ProgramsPhilip Schwarz
Tagless Final Encoding - Algebras and Interpreters and also Programs - An introduction, through the work of Gabriel Volpe.
Slide deck home: http://fpilluminated.com/assets/tagless-final-encoding-algebras-interpreters-and-programs.html
Let's make a contract: the art of designing a Java APIMario Fusco
An API is what developers use to achieve some task. More precisely it establishes a contract between them and the designers of the software exposing its services through that API. In this sense we're all API designers: our software doesn't work in isolation, but becomes useful only when it interacts with other software written by other developers. When writing software we're not only consumers, but also providers of one or more API and that's why every developer should know the features of a good API. During this presentation we will go through real-world examples, also taken from the standard Java API, of good and bad API and comment them in order to show the dos and don'ts of API design. More in general we will discuss the characteristics of an easy and pleasant to use API, like consistency, discoverability and understandability, together with some basic concepts like the principle of least astonishment, and find out how to achieve them.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Philip Schwarz
(download for perfect quality) - See how recursive functions and structural induction relate to recursive datatypes.
Follow along as the fold abstraction is introduced and explained.
Watch as folding is used to simplify the definition of recursive functions over recursive datatypes
Part 1 - through the work of Richard Bird and Graham Hutton.
This version corrects the following issues:
slide 7, 11 fib(0) is 0,rather than 1
slide 23: was supposed to be followed by 2-3 slides recapitulating definitions of factorial and fibonacci with and without foldr, plus translation to scala
slide 36: concat not invoked in concat example
slides 48 and 49: unwanted 'm' in definition of sum
throughout: a couple of typographical errors
throughout: several aesthetic imperfections (wrong font, wrong font colour)
Domain Driven Design with the F# type System -- NDC London 2013Scott Wlaschin
(Video of these slides here http://fsharpforfunandprofit.com/ddd)
Statically typed functional programming languages like F# encourage a very different way of thinking about types. The type system is your friend, not an annoyance, and can be used in many ways that might not be familiar to OO programmers.
Types can be used to represent the domain in a fine-grained, self documenting way. And in many cases, types can even be used to encode business rules so that you literally cannot create incorrect code. You can then use the static type checking almost as an instant unit test — making sure that your code is correct at compile time.
In this talk, we'll look at some of the ways you can use types as part of a domain driven design process, with some simple real world examples in F#. No jargon, no maths, and no prior F# experience necessary.
Code, links to video, etc., at http://fsharpforfunandprofit.com/ddd
For more on DDD and F# see:
http://fsharpforfunandprofit.com/ddd/
http://tomasp.net/blog/type-first-development.aspx/
http://gorodinski.com/blog/2013/02/17/domain-driven-design-with-fsharp-and-eventstore/
The lazy programmer's guide to writing thousands of testsScott Wlaschin
We are all familiar with example-based testing, as typified by TDD and BDD, where each test is hand-crafted.
But there's another approach to writing tests. In the "property-based testing" approach, a single test is run hundreds of times with randomly generated inputs. Property-based testing is a great way to find edge cases, and also helps you to understand and document the behavior of your code under all conditions.
This talk will introduce property-based testing, show you how it works, and demonstrate why you should consider adding this powerful technique to your toolbelt.
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.
An overview of functional programming. You can do functional programming in any language, it’s just that some languages push you toward this style. There are many styles of programming, depending on the dimension you look at and the features available in the language: Imperative vs Functional, Compiled vs Scripting, Static vs Dynamic, Implicit vs Explicit type conversion, Managed vs Unmanaged (memory). We'll talk about these concepts.
Github: https://github.com/ijcd
Twitter: @ijcd
San Francisco, California
Architectural Patterns in Building Modular Domain ModelsDebasish Ghosh
The main theme of the talk is how to use algebraic and functional techniques to build modular domain models that are pure and compositional even in the presence of side-effects. I discuss the use of pure algebraic effects to abstract side-effects thereby keeping the model compositional.
This is going to be a discussion about design patterns. But I promise it’s going to be very different from the Gang of Four patterns that we all have used and loved in Java.
It doesn’t have any mathematics or category theory - it’s about developing an insight that lets u identify code structures that u think may be improved with a beautiful transformation of an algebraic pattern.
In earlier days of Java coding we used to feel proud when we could locate a piece of code that could be transformed into an abstract factory and the factory bean could be injected using Spring DI. The result was we ended up maintaining not only Java code, but quite a bit of XML too, untyped and unsafe. This was the DI pattern in full glory. In this session we will discuss patterns that don’t look like external artifacts, they are part of the language, they have some mathematical foundations in the sense that they have an algebra that actually compose and compose organically to evolve larger abstractions.
DSL - expressive syntax on top of a clean semantic modelDebasish Ghosh
Does a DSL mean compromising the domain model purity for an ultra-expressive syntax. This presentation discusses how to evolve your DSL syntax as a sublanguage of combinators on top of an expressive domain model.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Domain Modeling in a Functional World
1. Domain Modeling in a
Functional World
some real life experiences
Monday 18 June 12
2. Debasish Ghosh
@debasishg on Twitter
code @
http://github.com/debasishg
blog @
Ruminations of a Programmer
http://debasishg.blogspot.com
Monday 18 June 12
3. What is Domain
Modeling
• We limit ourselves strictly to how the
domain behaves internally and how it
responds to events that it receives from
the external context
• We think of a domain model as being
comprised of the core granular
abstractions that handle the business logic
and a set of coarser level services that
interacts with the external world
Monday 18 June 12
4. Agenda
Immutability and algebraic data types
Updating domain models, functionally
Type classes & domain modeling
Models of computation
Managing states - the functional way
A declarative design for domain service layer
Monday 18 June 12
5. Functional domain
models
Immutability and algebraic data types
Updating domain models, functionally
Type classes & domain modeling
Models of computation
Event Sourcing
A declarative design for domain service layer
Monday 18 June 12
6. Immutability
• Immutable data
✦ can be shared freely
✦ no shared mutable state and hence no
locks, semaphores etc.
✦ and you get some parallelism free
Monday 18 June 12
7. Immutability
• Algebraic Data Types for representation of
domain entities
• Immutable structures like type-lenses for
functional updates
• No in-place mutation
• Heavy use of persistent data structures
Monday 18 June 12
8. Algebraic Data Types
Ok .. I get the Data Type part, but give me
the ALGEBRA ...
Monday 18 June 12
9. Algebraic Data Types
• For simplicity let’s assume that an algebraic
data type induces an algebra which gives us
some structures and some functions (or
morphisms or arrows) to manipulate. So we
have some types and some functions that morph
one type into another
• Well .. almost .. it’s actually an initial algebra,
but let’s stop at that without sounding more
scary
Monday 18 June 12
10. Rather we look at
some examples ..
• Unit represented by 1
• Optional data type represented as Option in
Scala (Maybe in Haskell) - a Sum type 1 + X
• Tuples represented as pairs (a, b) - the simplest
Product type
• Recursive data types - Lists of X represented by
L=1+X*L
• Binary Trees, represented as B = 1 + X * B2
Monday 18 June 12
11. A Taste of Algebra
unit type
• A List[Int] can be either an empty list or
consisting of one integer, or two integers, or three etc.
sum type
product type
• So a list of integers can be represented algebraically
as
1 + int + int * int + int * int * int + ... OR
1 + int + int ** 2 + int ** 3 + ..
Monday 18 June 12
12. and that’s not all ..
• we can have Taylor series expansion,
Composition, and even Differentiation on
types ..
Monday 18 June 12
13. and that’s not all ..
een
llow
Ha
r a
fo
em ion
th series expansion,
• we can have e cuss
Taylor
rv and even Differentiation on
se d
Composition, is
re..
can
types
we
Monday 18 June 12
14. Product Type
Formal Definition from Bob Harper PFPL
Chapter 14 :
“The binary product of two types consists of
ordered pairs of values, one from each type in the
order specified. The associated eliminatory forms
are projections, which select the first and second
component of a pair. The nullary product, or unit
type consists solely of the unique null tuple of no
values, and has no associated eliminatory form”
Monday 18 June 12
15. Product Type
• Implemented through case classes in Scala
• In a domain model we represent entities
using product types
• A tuple is the simplest product type :
val point = (x_cord, y_cord)
Monday 18 June 12
17. Sum Type
Formally from Bob Harper in PFPL, Chapter 15 :
“Most data structures involve alternatives such as the
distinction between a leaf and an interior node in a tree,
or a choice in the outermost form of a piece of abstract
syntax. Importantly, the choice determines the structure
of the value. For example, nodes have children, but leaves
do not, and so forth. These concepts are expressed by
sum types, specifically the binary sum, which offers a
choice of two things, and the nullary sum, which offers a
choice of no things”
Monday 18 June 12
18. Sum Type
• Implemented through subtyping in Scala
• Option is one of the most commonly used
sum type
sealed abstract class Option[+A] extends Product with
Serializable //..
final case class Some[+A](x: A) extends
Option[A] //..
case object None extends Option[Nothing] //..
Monday 18 June 12
19. Representation as
ADTs (sum type)
// various tax/fees to be paid when u do a trade
sealed trait TaxFeeId extends Serializable
case object TradeTax extends TaxFeeId
case object Commission extends TaxFeeId
case object VAT extends TaxFeeId
Monday 18 June 12
20. ADTs & Domain
Modeling
• Encouraging immutability
• In Scala you can use vars to have mutable case
classes, but that’s not encouraged
• With Haskell algebraic data types are
immutable values and you can use things like
the State monad for implicit state update
• There are some specialized data structures that
allow functional updates e.g. Lens, Zipper etc.
Monday 18 June 12
21. Agenda
Immutability and algebraic data types
Updating domain models, functionally
Type classes & domain modeling
Models of computation
Managing states - the functional way
A declarative design for domain service layer
Monday 18 June 12
22. Updating a Domain
Structure functionally
• A Type-Lens is a data structure that sets up
a bidirectional transformation between a
set of source structures S and target
structures T
• A Type-Lens is set up as a pair of functions:
• get S -> T
• putBack (S X T) -> S
Monday 18 June 12
23. Type Lens in Scala
case class Lens[A, B] (
get: A => B,
set: (A, B) => A
) //..
Monday 18 June 12
24. A Type Lens in Scala
// change ref no
val refNoLens: Lens[Trade, String] =
Lens((t: Trade) => t.refNo,
(t: Trade, r: String) => t.copy(refNo = r))
a function that takes a
trade and returns it’s reference no a function that updates a
trade with a supplied reference no
Monday 18 June 12
25. Lens under Composition
• What’s the big deal with a Type Lens ?
✦ Lens compose and hence gives you a cool
syntax to update nested structures within
an ADT
def addressL: Lens[Person, Address] = ...
def streetL: Lens[Address, String] = ...
val personStreetL: Lens[Person, String] =
streetL compose addressL
Monday 18 June 12
26. Lens under
composition
Using the personStreetL lens we may access or
set the (indirect) street property of a Person instance
val str: String =
personStreetL get person
val newP: Person =
personStreetL set (person, "Bob_St")
Monday 18 June 12
27. Functional updates in our
domain model using Type Lens
// change ref no
val refNoLens: Lens[Trade, String] =
Lens((t: Trade) => t.refNo,
(t: Trade, r: String) => t.copy(refNo = r))
// add tax/fees
val taxFeeLens: Lens[Trade, Option[List[(TaxFeeId, BigDecimal)]]] =
Lens((t: Trade) => t.taxFees,
(t: Trade, tfs: Option[List[(TaxFeeId, BigDecimal)]]) =>
t.copy(taxFees = tfs))
// add net amount
val netAmountLens: Lens[Trade, Option[BigDecimal]] =
Lens((t: Trade) => t.netAmount,
(t: Trade, n: Option[BigDecimal]) => t.copy(netAmount = n))
// add value date
val valueDateLens: Lens[Trade, Option[Date]] =
Lens((t: Trade) => t.valueDate,
(t: Trade, d: Option[Date]) => t.copy(valueDate = d))
Monday 18 June 12
28. Agenda
Immutability and algebraic data types
Updating domain models, functionally
Type classes & domain modeling
Models of computation
Managing states - the functional way
A declarative design for domain service layer
Monday 18 June 12
29. Type class
• Ad hoc polymorphism
• Open, unlike subtyping - makes more sense
in domain modeling because domain rules
also change. Useful for designing open APIs
which can be adapted later to newer types
• Leads to generic, modular and reusable
code
Monday 18 June 12
30. Useful type classes behind
your domain model
• Functor - offers you the capability to map
over a structure. And not surprisingly, it has a
single method: map
trait Functor[F[_]] {
def map[A, B](fa: F[A])(f: A => B): F[B]
//..
}
Monday 18 June 12
31. More type classes
• Applicative Functors - Beefed up functors. Here
the function is wrapped within a functor. So we
lift a function wrapped in a functor to apply on
another functor
trait Applicative[F[_]] extends Functor {
def apply[A, B](f: F[A => B]): F[A] => F[B]
def pure[A](a: A): F[A]
//..
}
Monday 18 June 12
32. More type classes
• Monads - beefed up Applicative Functor, where in
addition to apply and map, you get a bind
(>>=) function which helps you bind a monadic
value to a function’s input that produces a
monadic output
trait Monad[F[_]] extends Applicative {
def >>=[A, B] (fa: F[A])(f: A => F[B]): F[B]
}
Monday 18 June 12
33. And some more ..
• Semigroup - a type class that offers an associative binary
operation
trait Semigroup[F] {
def append(f1: F, f2: => F): F
//..
}
• Monoid - a Semigroup with an identity element
trait Monoid[F] extends Semigroup[F] {
def zero: F
//..
}
Monday 18 June 12
34. Accumulating validation
errors using Type Classes
• We can use Semigroup to accumulate
errors in our domain validation logic
• Semigroup is an abstraction that offers an
associative binary append operation -
looks intuitive for our use case
Monday 18 June 12
35. Accumulating validation
errors using Type Classes
sealed trait Validation[+e, +A] {
def append[EE >: E, AA >: A](that: Validation[EE, AA])
(implicit es: Semigroup[EE], as: Semigroup[AA])
: Validation[EE, AA] = (this, that) match {
// both Success: combine results using Semigroup
case (Success(a1), Success(a2)) =>
Success(as.append(a1, a2))
// one side succeeds : return success value
case (v1@Success(a1), Failure(_)) => v1
case (Failure(_), v2@Success(a2)) => v2
// both Failures: combine errors using Semigroup
case (Failure(e1), Failure(e2)) =>
Failure(es.append(e1, e2))
}
Monday 18 June 12
36. Type Classes - effective
for the domain model
• A small data structure like Semigroup has a
big effect in our functional domain model
• How does something with just an
associative binary operation be so
effective ?
• The secret sauce is in the power of
function composition and the ability to
implement type classes on any abstraction
Monday 18 June 12
37. // using Validation as an applicative
// can be combined to accumulate exceptions
def makeTrade(account: Account, instrument: Instrument,
refNo: String, market: Market, unitPrice: BigDecimal,
quantity: BigDecimal) =
(validUnitPrice(unitPrice).liftFailNel |@|
validQuantity(quantity).liftFailNel) { (u, q) =>
Trade(account, instrument, refNo, market, u, q)
}
an applicative builder
Monday 18 June 12
38. // validate quantity
def validQuantity(qty: BigDecimal): Validation[String,
BigDecimal] =
if (qty <= 0) "qty must be > 0".fail
else if (qty > 500) "qty must be <= 500".fail
else qty.success
// validate unit price
def validUnitPrice(price: BigDecimal):
Validation[String, BigDecimal] =
if (price <= 0) "price must be > 0".fail
else if (price > 100) "price must be <= 100".fail
else price.success
Monday 18 June 12
39. So far in the type class
world ..
• Type classes lead to design of abstractions that
can be extended post hoc
• Type classes and higher order functions is a
potent combo of ad hoc polymorphism and
function composition
• Don’t ignore small abstractions like Semigroup
and Monoid - when placed in the proper
context, they can contribute to writing succinct
code for your domain model
Monday 18 June 12
40. Composability FTW
• Functions compose mathematically. Same
for functional programming (a big
assumption - no side-effects)
• Side-effects don’t compose. All functional
programming languages encourage isolating
side-effects from pure domain logic .. and
some do enforce through the type system
Monday 18 June 12
41. For your domain model ..
Decouple pure logic
from side-effects ..
domain rules isolated
from impure stuff
easier to
unit test
flexible reordering of
operations - easier
parallelism
easier to reason
about your logic
Monday 18 June 12
42. What is composition ?
• compose - v. to make or create by putting
together parts or elements
• a bottom up way of creating bigger
abstractions from smaller ones
• combinators FTW
Monday 18 June 12
43. Combinators
“a function which builds program fragments from program
fragments; in a sense the programmer using combinators
constructs much of the desired program automatically, rather
than writing every detail by hand”
- John Hughes
Generalising Monads to Arrows
(http://www.cse.chalmers.se/~rjmh/Papers/arrows.pdf)
Monday 18 June 12
44. Combinators act as the
glue ..
• map
• filter
• bind
• apply
• ...
Monday 18 June 12
45. Pure functions as
domain behaviors
// value a tax/fee for a specific trade
val valueAs:
Trade => TaxFeeId => BigDecimal = {trade => tid =>
((rates get tid) map (_ * principal(trade)))
getOrElse (BigDecimal(0))
}
// all tax/fees for a specific trade
val taxFeeCalculate:
Trade => List[TaxFeeId] => List[(TaxFeeId, BigDecimal)] = {t =>
tids =>
tids zip (tids map valueAs(t))
}
Monday 18 June 12
46. Pure functions as
domain behaviors
// value a tax/fee for a specific trade
val valueAs:
Trade => TaxFeeId => BigDecimal = {trade => tid =>
map
((rates get tid) map (_ * principal(trade)))
getOrElse (BigDecimal(0))
}
// all tax/fees for a specific trade
val taxFeeCalculate:
Trade => List[TaxFeeId] => List[(TaxFeeId, BigDecimal)] = {t =>
tids =>
zip map
tids zip (tids map valueAs(t))
}
combinators
Monday 18 June 12
47. Pure functions as
domain behaviors
// value a tax/fee for a specific trade
val valueAs:
Trade => TaxFeeId => BigDecimal = {trade => tid =>
map
((rates get tid) map (_ * principal(trade)))
getOrElse (BigDecimal(0))
}
// all tax/fees for a specific trade
val taxFeeCalculate:
Trade => List[TaxFeeId] => List[(TaxFeeId, BigDecimal)] = {t =>
tids =>
zip map
tids zip (tids map valueAs(t))
}
combinators
Monday 18 June 12
48. // enrich a trade with tax/fees and compute net value
val enrichTrade: Trade => Trade = {trade =>
val taxes = for {
// get the tax/fee ids for a trade
taxFeeIds <- forTrade
// calculate tax fee values
taxFeeValues <- taxFeeCalculate
}
yield(taxFeeIds map taxFeeValues)
val t = taxFeeLens.set(trade, taxes(trade))
netAmountLens.set(t,
t.taxFees.map(_.foldl(principal(t))
((a, b) => a + b._2)))
}
Monday 18 June 12
49. monadic chaining for
an expressive DSL
val trds =
for {
trade <- trades
trValidated <- validate(trade)
trEnriched <- enrich(trValidated)
trFinal <- journalize(trEnriched)
}
yield trFinal
Monday 18 June 12
50. Agenda
Immutability and algebraic data types
Updating domain models, functionally
Type classes & domain modeling
Models of computation
Managing states - the functional way
A declarative design for domain service layer
Monday 18 June 12
51. The palette of
computation models
the applicative model
to construct trades
with accumulating validation
errors
the monadic model the arrow model
that chains computation of computation
and gives us a nice DSL that generalizes monads
for trade lifecycle
Monday 18 June 12
52. The Arrow model of
computation
a monad lifts a value
A => M[A] into a computation
an arrow lifts a function
from input to output
(B => C) => A[B,C] into a computation
If the function is of the form A => M[B]
then we call the arrow a Kleisli
Monday 18 June 12
53. Back to our domain model
- from Orders to Trades
1. process client orders
2. execute in the market
3. allocate street side trades to client
accounts
Monday 18 June 12
54. def tradeGeneration(market: Market, broker: Account,
clientAccounts: List[Account]) =
// client orders
kleisli(clientOrders)
// executed at market by broker
>=> kleisli(execute(market)(broker))
// and allocated to client accounts
>=> kleisli(allocate(clientAccounts))
Monday 18 June 12
55. Agenda
Immutability and algebraic data types
Updating domain models, functionally
Type classes & domain modeling
Models of computation
Managing states - the functional way
A declarative design for domain service layer
Monday 18 June 12
56. Managing States
• But domain objects don’t exist in isolation
• Need to interact with other objects
• .. and respond to events from the external
world
• .. changing from one state to another
Monday 18 June 12
57. A day in the life of a
Trade object
tax/fee added
created value date added ssi added
net value computed
a Trade object
ready for settlement
Monday 18 June 12
58. What’s the big deal ?
All these sound like changing states of a newly created
Trade object !!
Monday 18 June 12
59. • but ..
• Changing state through in-place mutation is
destructive
• We lose temporality of the data structure
• The fact that a Trade is enriched with tax/
fee NOW does not mean it was not valued
at 0 tax SOME TIME BACK
Monday 18 June 12
60. What if we would like to have our
system rolled back to THAT POINT IN
TIME ?
Monday 18 June 12
62. • The solution is to keep information in such a
way that we have EVERY BIT OF DETAILS
stored as the object changes from one state
to another
• Enter Event Sourcing
Monday 18 June 12
63. Event Sourcing
• Preserves the temporality of the data
structure
• Represent state NOT as a mutable object,
rather as a sequence of domain events that
took place right from the creation till the
current point in time
• Decouple the state of the object from its
identity. The state changes over time,
identity is IMMUTABLE
Monday 18 June 12
64. Domain Events as
Behaviors
NewTrade AddValueDate EnrichTrade
state = Created state = ValueDateAdded state = Enriched
persisted with timestamp t0 persisted with timestamp t2
persisted with timestamp t1
(t2 > t1 > t0)
Monday 18 June 12
65. .. and since we store every event that hits the system we
have the ability to recreate ANY previous state of the
system starting from ANY point in time in the past
Monday 18 June 12
66. Events and States
sealed trait TradingEvent extends Event
case object NewTrade extends TradingEvent
case object EnrichTrade extends TradingEvent
case object AddValueDate extends TradingEvent
case object SendOutContractNote extends TradingEvent
sealed trait TradeState extends State
case object Created extends TradeState
case object Enriched extends TradeState
case object ValueDateAdded extends TradeState
Monday 18 June 12
67. The Current State
• How do you reflect the current state of the
domain object ?
✦ start with the initial state
✦ manage all state transitions
✦ persist all state transitions
✦ maintain a snapshot that reflects the
current state
✦ you now have the ability to roll back to
any earlier state
Monday 18 June 12
68. The essence of Event
Sourcing
Store the events in a durable repository.They are
the lowest level granular structure that model
the actual behavior of the domain.You can
always recreate any state if you store events
since the creation of the domain object.
Monday 18 June 12
69. The Duality
• Event Sourcing keeps a • In functional
trail of all events that programming, data
the abstraction has structures that keep
handled track of their history are
called persistent data
• Event Sourcing does not structures. Immutability
taken to the next level
ever mutate an existing
record
• An immutable data
structure does not
mutate data - returns a
newer version every
time you update it
Monday 18 June 12
70. Event Sourced Domain
Models
• Now we have the domain objects receiving
domain events which take them from state
A to state B
• Will the Trade object have all the event
handling logic ?
• What about state changes ? Use the Trade
object for this as well ?
Monday 18 June 12
71. Separation of concerns
• The Trade object has the core business of
the trading logic. It manifests all state
changes in terms of what it contains as data
• But event handling and managing state
transitions is something that belongs to the
service layer of the domain model
Monday 18 June 12
72. Separation of Concerns
• The service layer • The core domain layer
✦ receives events from ✦ implements core
the context trading functions like
calculation of value
✦ manages state date, trade valuation,
transitions tax/fee handling etc
✦ delegates to Trade ✦ completely oblivious
object for core of the context
business
✦ notifies other
subscribers
Monday 18 June 12
73. Agenda
Immutability and algebraic data types
Updating domain models, functionally
Type classes & domain modeling
Models of computation
Managing states - the functional way
A declarative design for domain service layer
Monday 18 June 12
74. The Domain Service
Layer
• Handles domain events and delegates to
someone who logs (sources) the events
• May need to maintain an in-memory
snapshot of the domain object’s current
state
• Delegates persistence of the snapshot to
other subscribers like Query Services
Monday 18 June 12
75. CQRS
• The service layer ensures a complete
decoupling of how it handles updates
(commands) on domain objects and reads
(queries) on the recent snapshot
• Updates are persisted as events while
queries are served from entirely different
sources, typically from read slaves in an
RDBMS
Monday 18 June 12
76. In other words, the domain
service layer acts as a state
machine
Monday 18 June 12
77. Making it Explicit
• Model the domain service layer as an FSM
(Finite State Machine) - call it the
TradeLifecycle, which is totally
segregated from the Trade domain object
• .. and let the FSM run within an actor
model based on asynchronous messaging
• We use Akka’s FSM implementation
Monday 18 June 12
78. FSM in Akka
• Actor based
✦ available as a mixin for the Akka actor
✦ similar to Erlang gen_fsm
implementation
✦ as a client you need to implement the
state transition rules using a declarative
syntax based DSL, all heavy lifting done by
Akka actors
Monday 18 June 12
79. initial state
match on event
AddValueDate
startWith(Created, trade)
start state of Trade
object
when(Created) {
case Event(e@AddValueDate, data) =>
log.map(_.appendAsync(data.refNo, Created, Some(data), e))
val trd = addValueDate(data)
gossip(trd)
goto(ValueDateAdded) using trd forMax(timeout)
}
notify observers log the event
move to next state
update data
of Trade lifecycle
structure
Monday 18 June 12
80. Handle events &
process data updates and state
changes
startWith(Created, trade) Log events (event sourcing)
when(Created) {
case Event(e@AddValueDate, data) =>
log.map(_.appendAsync(data.refNo, Created, Some(data), e))
val trd = addValueDate(data)
gossip(trd)
goto(ValueDateAdded) using trd forMax(timeout)
}
Notifying Listeners
Monday 18 June 12
81. State change -
functionally
// closure for adding a value date
val addValueDate: Trade => Trade = {trade =>
valueDateLens.set(trade, ..)
}
pure referentially transparent implementation
Monday 18 June 12
82. Notifying Listeners
• A typical use case is to send
updates to the Query
subscribers as in CQRS
• The query is rendered from a
separate store which needs to
be updated with all changes that
go on in the domain model
Monday 18 June 12
83. Notifications in Akka
FSM
trait FSM[S, D] extends Listeners {
//..
}
Listeners is a generic trait to implement
listening capability on an Actor
trait Listeners {self: Actor =>
protected val listeners = ..
//..
protected def gossip(msg: Any) =
listeners foreach (_ ! msg)
//..
}
Monday 18 June 12
84. class TradeLifecycle(trade: Trade, timeout: Duration,
log: Option[EventLog])
extends Actor with FSM[TradeState, Trade] {
import FSM._
startWith(Created, trade)
domain service as
a Finite State Machine
when(Created) {
case Event(e@AddValueDate, data) =>
log.map(_.appendAsync(data.refNo, Created, Some(data), e)) • declarative
val trd = addValueDate(data) • actor based
gossip(trd) • asynchronous
goto(ValueDateAdded) using trd forMax(timeout) • event sourced
}
when(ValueDateAdded) {
case Event(StateTimeout, _) =>
stay
case Event(e@EnrichTrade, data) =>
log.map(_.appendAsync(data.refNo, ValueDateAdded, None, e))
val trd = enrichTrade(data)
gossip(trd)
goto(Enriched) using trd forMax(timeout)
}
//..
}
Monday 18 June 12
85. // 1. create the state machine
val tlc =
system.actorOf(Props(
new TradeLifecycle(trd, timeout.duration, Some(log))))
// 2. register listeners
tlc ! SubscribeTransitionCallBack(qry)
// 3. fire events
tlc ! AddValueDate
tlc ! EnrichTrade
val future = tlc ? SendOutContractNote
// 4. wait for result
finalTrades += Await.result(future, timeout.duration)
.asInstanceOf[Trade]
Monday 18 June 12
86. // check query store
val f = qry ? QueryAllTrades
val qtrades = Await.result(f,timeout.duration)
.asInstanceOf[List[Trade]]
// query store in sync with the in-memory snapshot
qtrades should equal(finalTrades)
Monday 18 June 12
87. Summary
• Functional programming is programming with functions -
design your domain model with function composition
as the primary form of building abstractions
• Have a clear delineation between side-effects and pure
functions. Pure functions are easier to debug and
reason about
• Immutability rocks - makes it way easier to share
abstractions across threads
• With immutable domain abstractions you can make
good use of transactional references through an STM
Monday 18 June 12