We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

Let's get functional

00:00

Formal Metadata

Title
Let's get functional
Title of Series
Number of Parts
46
Author
License
CC Attribution 3.0 Unported:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal purpose as long as the work is attributed to the author in the manner specified by the author or licensor.
Identifiers
Publisher
Release Date
Language

Content Metadata

Subject Area
Genre
Abstract
Find more information here: http://15.droidcon.de/session/lets-get-functional Ever tried functional languages ? Ever been annoyed that every time you get see the same Fibonacci examples or yet another maths problem ? So what can functional languages really teach us on our day to day life as Java devs ? This talk will take some concrete examples and show you how some functional approaches will make your life easier. We will see how we can try and bring functional and immutability to our "beloved" Android Java 7 and what this brings us. We'll be exploring libraries such as RxJava, Auto-Value, Retrolambda and such and see how they can help us shape a more functional Java.
18
Drop (liquid)RobotAndroid (robot)SoftwareSoftware testingCodeFunctional programmingProgramming paradigmFunctional programmingLecture/Conference
RobotFunctional programmingVariable (mathematics)ResultantOrder (biology)Utility softwareLevel (video gaming)High-level programming languageLambda calculusSocial classDeclarative programmingLecture/Conference
RobotCore dumpFunctional programmingFunctional programmingMultiplication signProgramming paradigmProgramming languageBitMedical imagingSingle-precision floating-point formatKey (cryptography)Meeting/Interview
CodeMaß <Mathematik>CodeCodeBoilerplate (text)WritingRight angleExecution unitLecture/ConferenceComputer animation
Focus (optics)Musical ensembleReading (process)WritingRight angleHigh-level programming languageProgramming languageProgramming paradigmSymbol tableBit rateElectronic mailing listLevel (video gaming)Hash functionCodeMeeting/InterviewLecture/ConferenceComputer animation
RobotFunctional programmingProgramming paradigmFunctional programmingCore dumpMedical imagingMeeting/InterviewLecture/Conference
Revision controlLecture/ConferenceMeeting/Interview
Computer programReal numberCache (computing)Meeting/Interview
Bit error rateRepetitionFunctional programmingResultantData managementAndroid (robot)PredictabilityoutputSoftware developerPresentation of a groupLecture/ConferenceMeeting/Interview
Connectivity (graph theory)Functional programmingKey (cryptography)Different (Kate Ryan album)Level (video gaming)Lecture/ConferenceMeeting/Interview
Menu (computing)outputFunction (mathematics)Sound effectSound effectFunctional programmingMereologyComputer programNumberDemosceneComputer animationMeeting/Interview
Bit error rateProgramming languageCodeGodLecture/Conference
Boilerplate (text)Programming languageJava appletFunctional programmingSoftware frameworkComputer animation
Java appletRepetitionJava appletSoftware developerFunctional programmingLibrary (computing)Software frameworkTransformation (genetics)Lambda calculusWordLecture/Conference
RobotSoftware frameworkSocial classObject (grammar)Library (computing)Boilerplate (text)Hash functionWritingFunctional programmingProcess (computing)Multiplication signJava appletPositional notationSynchronizationLimit (category theory)Meeting/Interview
Java appletComputer fileProgramming language
Mobile appCodeMereologyProgramming languageJava appletLecture/ConferenceMeeting/Interview
Lambda calculusString (computer science)Interior (topology)Parameter (computer programming)Lambda calculusString (computer science)Parameter (computer programming)Line (geometry)Functional programmingInterior (topology)Computer animation
Programming languageCodeJava appletLecture/ConferenceMeeting/Interview
Electronic mailing listWordMultiplication signLecture/Conference
Set (mathematics)Line (geometry)WordFocus (optics)CodeStatement (computer science)Level (video gaming)Hash functionBit rateComputer animation
Local GroupCountingCode refactoringQuicksortLevel (video gaming)CountingWordHash functionBitCurveGroup actionIterationKey (cryptography)Computer animation
CodeCodeElectronic program guideProgramming languageCodeDesign by contractPoint (geometry)Software bugArithmetic meanLine (geometry)WordLecture/ConferenceMeeting/Interview
CodeMultiplication signWordExtension (kinesiology)CountingLecture/Conference
Thresholding (image processing)Digital filterCountingElectronic mailing listLoop (music)Thresholding (image processing)Element (mathematics)ExpressionLine (geometry)Boilerplate (text)Lecture/ConferenceComputer animation
Focus (optics)Product (business)CASE <Informatik>
RobotProcess (computing)Electronic mailing listoutputFunction (mathematics)Electronic mailing listProduct (business)Endliche ModelltheorieCartesian coordinate systemObject (grammar)Transformation (genetics)Process (computing)outputLogicFunction (mathematics)BitSoftwareCore dumpElectronic visual displayView (database)Meeting/InterviewComputer animation
RepetitionGastropod shellGastropod shellNeuroinformatikScripting languageComputer fileBitMultiplication signMathematicsFunctional programmingConnectivity (graph theory)Domain nameProgramming languageCartesian coordinate systemLecture/ConferenceMeeting/InterviewComputer animation
Electronic mailing listFunction (mathematics)Digital filterProcess (computing)CurvatureFunctional programmingLevel (video gaming)Electronic mailing listProgramming languageHelmholtz decompositionConnectivity (graph theory)BitGastropod shellExistenceFunctional programmingElement (mathematics)Lecture/Conference
Electronic mailing listLevel (video gaming)Element (mathematics)Total S.A.Lecture/Conference
LogicElement (mathematics)Protein foldingFunction (mathematics)Electronic mailing listMultiplication signMessage passingElement (mathematics)Functional programmingResultantBitIterationComputer animationXML
Protein foldingMaxima and minimaMaxima and minimaElectronic mailing listElement (mathematics)ResultantIterationFunctional programmingTraverse (surveying)Default (computer science)Key (cryptography)Computer animation
Traverse (surveying)Electronic mailing listResultantCodeNeuroinformatikMobile appTotal S.A.Meeting/InterviewLecture/Conference
Total S.A.Protein foldingString (computer science)Multiplication signPoint (geometry)Loop (music)IterationTotal S.A.SummierbarkeitProcess (computing)Boilerplate (text)Initial value problemTurtle graphicsLecture/ConferenceMeeting/InterviewComputer animation
GodComputer animationXML
Computer iconCodeMultiplication signFunctional programmingPredictabilityMathematicsEndliche ModelltheorieSound effectLecture/ConferenceMeeting/Interview
RobotFocus (optics)Functional programmingProjective planeProcess (computing)Control flowProgramming languageMeeting/InterviewLecture/Conference
Point (geometry)Projective planeLecture/Conference
Point (geometry)Functional programmingGoodness of fitComputer animationLecture/Conference
RobotJava appletComputer programmingFunctional programmingAuthorizationProbability density functionMultiplication signFreewareReading (process)Java appletRevision controlComputer programFunctional programmingProgramming languageWeb pageTheoryCategory of beingBlogBitLecture/ConferenceMeeting/InterviewXMLComputer animation
Programming languageMathematicsParallel portMeeting/InterviewLecture/Conference
Transcript: English(auto-generated)
Thank you, so hi, I'm Benjamin. I work as an Android software craftsman at Novoda So Novoda is an Android only agency. We are based in Berlin London livable and now even Barcelona and
The reason I'm talking to you today is because at Novoda we proud ourselves in creating clean code tested code and I'm Myself a strong advocate of learning from functional languages Functional paradigms to enable ourselves to write cleaner
easier to test code So let's talk about what is functional programming as The name suggests it's about using function as first-class citizen that means Being able to use functions the way you are using your usual data variables you can
Keep a hold on them pass them around and compose functionality this means having high-order functions a high-order function means that you have a Function that can take another function or even return a function as a result we can use that to create
Compose and have a high-level language a high-level way of expressing ourselves To create the goal. We're trying to achieve This means having the ability to declare Lambdas So lambda is an anonymous function and the idea is really to be able to lift away the pain of having to declare a
Class to create a method or having to declare a utility function if we need something right now We can declare it as a lambda and pass it around another core concept and functional languages is Immutability and I will dive a bit more later into those concepts
but the main key that I want to I want to get to you is It can be enforced by languages. We have languages helping ourselves to enforce those paradigms, but it doesn't need to be You can do that yourself Same thing we talk about fuel function those are like concepts which every single time people talk about functional languages
it's all about all of this language is pure or this language is whatever and It can be enforced by language, but it doesn't need to be so Let's back up a bit. Why are we even talking about this? Why should you try and understand? What is a functional? approach to solving a problem
so the main idea is We want to Ryan to write smaller codes. We want to write codes that we can glance over and understand We want to write more expressive codes We want to get like remove all the boilerplate all that let useless code that is only there to help us achieve our goal not expressing what we want to do and
We want to write small units. We want to write pieces of code that we can reuse we can fully test and have control over But the main idea is we want to focus on what not on how? Who here in the room is like a musician or knows how to like read music write music?
Good, so you're probably using this that is the way you interact with music a music sheet It's the language of notes and symbols that allow us to express What the music is supposed to sound like is it small is it forte?
What what tonality is it and this is a high-level language that allows us to express ourselves? You're not using this you're not Representing how the sound is moving the air to get to your ears because there's no way you can actually create something beautiful using this
let alone understand what's happening and That's what we want to achieve with code Why do we have to focus on iterating through a list to do things like having a hash map of? Items we want a high-level language higher than what we have right now to understand concepts
Paradigms what we try to achieve with our data, and this is what functional languages and functional paradigms allow you to do So what are those core concepts? So as I mentioned the first one is image ability and as the name suggests it means nothing can change Wait a minute we do need to make things change right so the idea is if we have a
Value and we don't we want to modify it Instead of mutating it. We're going to create a new value that represents the modified version So why do we want to do that? Why do we want to use this with concept which doesn't sound really natural?
It's actually to solve a way more bigger problem that Seems even less natural so imagine that I have an apple in my hand. I take a bite, and I give it to you Once you have it in your hand. I have no way to modify that apple I'm not going to take another bite in it and change it for you. You have it you hold it
But this isn't a real world We're talking about program if I give to you a value I can keep a reference to it, and if I could take another bite in it all of a sudden You're holding something that changes this is completely non-natural this is something we don't expect and
Those things we can't reason with it It's too far out of our way of conceiving things for us to be able to Properly understand them, so we want to avoid that and to avoid that If I take a copy of that apple and give it to you It's a different one and if the way that apple is designed
Prevents me from modifying it then you're safe You're safe to cache values Yourself to keep a hold on something as long as you want and you know that the only reason it's going to change is Because you decide and pure function So a pure function the idea is it's a function that will always give the same result
if I always give it the same input and Once again, it's about predictability. It's about understanding easily. What's happening I can take an example In Android who here has worked with the account manager
Remember this nice get account methods and you call get account and if the account is not there on the device It will fire up an activity Prompting the user to log in create an account and then return the account to you but if the account is there on a device it will Just return the account as a developer when I call that method. I have no way of knowing
What's going to happen? It's not predictable, and this is confusing and You can solve that problem by saying I'm going to split that into several functions. I'm going to have is the account present I'm going to have create an account I'm going to have to get an account and now I have a predictable way of
Using those those methods, and they're always going to return the same thing so breaking it down into smaller components and one of the key principles if something is Represented using multiple values or using functions that might return different things during different circumstances
Usually it's because you haven't broken down the problem enough. You're not at the correct level so What I mentioned is No side effects, so when someone said no side effect that that's what they mean they mean we want that function to be predictable
We wanted to not do anything else apart from what it's saying get user should return to me a user It shouldn't do anything else and This is to achieve what we call Referential transparency and what this means is if I have get user I can replace it By the user and not change the behavior of my program
If I get user and it's creating the user if it's not there if I just replace it by the user the account is not created And this creates problems. I have no way of understanding. What's happening behind the scenes All in on what we want is reducing the number of moving parts. We want to avoid asking that question. What is this doing?
We want things that are simple enough to understand them. We want to have predictable code that we can reason with Okay, you're going to tell me. Oh my God. This is a nice idea, but it's really crazy What language can I use to do that? I'm going to have to use Haskell all those weird languages that nobody wants to see
Well, it's not true. You can use any language really Some languages are going to be easier to implement those concepts in less boilerplates to do them But you can use Java C++ python and of course you can use more functional languages such as coffins kala and so on and so forth
But the key idea is it's not about the language. It's not about the framework It's about the ideas and the way you approach a problem so I Know we're all Android developers here at least a lot of us So let's talk about Java 7 and lower because that's kind of what we're stuck with
so You can use toolkits frameworks libraries such as our x Java or functional Java to help you bring Lambdas some collections transformation and things that come from the functional world into the Java word and This is really nice. We can use those libraries of framework to help us avoid boilerplate to apply those principles
We can use auto value if you want to write immutable collection immutable values Or collections in an easier way auto value is a really nice library it uses annotation processing to
generate classes with equals hash code and all those boilerplate functions that you have to reimplement every single time you create a value object and Most importantly it will enforce that things can't be null it will enforce That you can't mutate things and it just helps you bring that to Java
But you don't have to I mean what about cutlin? Who here was in the cutlin talk yesterday? Most of us so cutlin is a really nice language and one of the thing I enjoy the most out of it Is it's fully compatible with Java as it was presented yesterday
You can use cutlin files in Java or Java files in cutlin So that means if you really need to do something in a functional way And you don't want to you know you don't want to do that everywhere in your app because you're not really certain yet So just take one part of your app you say that thing is quite complex I want to to migrate it to a functional way and you do it in cutlin and
Then you don't need to change the rest of your code It's it's a really nice way to slowly get into it And it's a really nice language to explore so I'm going to use cutlin and the rest of my talk for snippets of code And if you've seen the talk yesterday you would say that it's quite similar to Java if you haven't been
The first line is a function that takes a string as a parameter and returns a string the second here is a higher the function that takes a parameter a Function as a parameter that takes an int and return an int and overall that things return an int And the last one is how you would define the lambda and this one takes two ints and sum them
So the syntax is not too far off from Java. It's actually quite easy to get used to and When I'm presenting some snippets of code later I'm going to present them in cutlin, but keep in mind those things get me impressed in any language
It's really about the way you're going to approach the problem more than using a toolkit or using something So let's get functional so This is a quite complex way of representing counting words if I want to have a collection of words and
I need to count how many occurrences of each word is in the list? Most of the time in an imperative way you would have to do something like that You're probably going to extract the if statement or some things to try and clean it up But there's going to be a fair amount of lines of code In here, I'm setting a hash map and iterating through the items and having some check
But all of that it focuses on the how it doesn't focus on the why glancing at this I don't realize Initially that it's actually counting words whereas I Can refactor this I can refactor this in a more functional way and? It might not look as easy to understand if you don't know the concepts, but you can agree with me. This is more concise
This is more concise, and if you look at it even without understanding the concepts you can see that this is words dot group by word It's already sort of Telling you what it's doing and the most important thing you don't have that
Iteration over items you don't have the concept of hash map or whatever the only thing you say is I'm grouping things By words, and I'm returning them as a pair of key and count And yes, it's a bit of a learning curve you need to learn those keywords grouping mapping and that But once you have them once you understand them
Then you can express things in a much more concise way, and you can express them as The what not the how this is expressing that I want to group items by words The other one was expressing that I wanted to store them by key value so
We want to ride self-explanatory codes anyone who has read Like clean codes or any other like kind of language guide we always talk about this. Let's write self-explanatory codes But that doesn't mean the method name should explain what it's doing as In yes, the method name should explain was doing I was calling it foo right there
Which is pretty silly, but it's to showcase a point if you call if you use the method name to explain What the method is doing it's as bad as just writing a big comment on top of it and say I'm done I explained it Two months down the line the code can have changed and the method name hasn't changed The method name doesn't represent what the code is doing anymore and that leads to bugs
We want that method name to be the contract with the rest of your code The way you understand what this is doing without going into seeing what that method is doing if I call that method I want to know what it's doing by reading it if I look at that method I need to be able to see what it's doing just by glancing at it
I need to understand straightaway what this method that says it's counting the occurrences of words Is it actually doing that I need to be able to check it quickly If we understand our code in this glanceable way and summarized way, then we want So we want to keep things small and concise
Okay, so it's also allowing for extensibility. So now if I take the same example Counting occurrences of words and now I want to count only the items that occurred at least three times I want to sort them by occurrences, and I only want to return the word not the count I
Can show it like this I will use functional concepts to compose over my list and say I have my Counter-occurrences, so that's the method from previously and I will filter on top of it I will sort on top of it, and I will map on top of it and Those things are quite concise the thing that actually represent what we're doing is this line, and it's quite expressive
I'm checking against a threshold I Am sorting it by the second element in my pair And we can even get more expressive by like extracting them into more meaningful names and so on and so forth But the key idea is we don't have all the boilerplate of what you would have to do with a for loop with an
if statement inside and so on and so forth So you're gonna. Tell me yeah, that's nice. What about real cases? What about what I'm gonna do tomorrow well all the things I just showed were real cases and If you don't trust me the only the only way you're gonna go from
Seeing something that you need to achieve to the way to achieve it functionally is focusing on the data focus on what you're manipulating You're probably manipulating article product users values Those values can be made imitable There these things the concrete objects you're manipulating in your application in your model
And Then you're probably handling lists of those so I have a list of users a list of products And upon those collection of values. I'm gonna do transformation Processing that's what we're doing. We're taking input and giving an output, so we're fetching a list of users
we are calculating the price of a basket those are things that you're going to do every day and This is taking an input of those values like list of values and and returning an output of those It's as simple as that if you if you consider the core of your application the model bit
This is what you're doing of course in the UI you're gonna be a bit more I want to display something in a text view I want to display things in a list view but Ultimately when you fetch data from the network when you order it sorted process it all that complex logic Can be expressed in a really functional way?
So think about it like shell when you do a shell Computation or something you're not going to do this you're not going to do a Script in a file and just run it every single time you're most likely going to do something like this You're going to use the tiny bits of command shell and pipe them together
Because you have those small reusable components that are the shell commands, and you combine them together and That way if tomorrow. I need to solve them differently. I don't need to go into my file change that file I just take this change that value here and all of a sudden. It does what I want
It's exactly the same thing What we want to do is Create a language of small functions from all domain functions that you can reuse in your application to deal with your data So in functional languages we have a lot of really really powerful tools above lists. We have the ability to
Map flat map filter things merge combine all those things Exists predefined for you just waiting for you to use them and combine them together and the idea is really try to Slowly get to know them and use them
You can extract things from this using first last and so on or you can use some more advanced concept like fold That I will get into a bit later The main idea is I want to see what I trying to achieve at Decompose it the way you would decompose your thinking in shell it's the same thing you try and decompose it into smaller components that can be expressed using those functions if
I want to only use some elements from a list It's going to be a filter if I want to transform the elements in the list is going to be a map and so on and so forth So let's take some examples if I want to display the saved articles in the list if I want to
Only fetch the items in a basket that requires an age check It's a filtering of a list all of that can be expressed using a list of items and a filter If I want to get the total of a basket if I want To find an item in the list anything that requires traversing a collection and producing a single output can be expressed using a fold
So what is falls is this some kind of dark magic? No, it's not. It's a simple concept that can be extended to the extreme fold is applying a function to every single item in your list and
Using the output of the previous iteration in the next one Let's be a bit more concrete so fx if Every single time I call it x is going to be the element in my list and y is the result of the previous Pass So let's apply it to something simple. I want to find the maximum in the list in here
I want to find the cutest squirrel So I will take my first element in my list and I need the accumulator So I will take a default value I will take a really not cute squirrel a really ugly one And I apply my function and I get the cutest out of the two What I'm going to do now is it's called again
it was going to be called with a second item in my list and the result of the previous iteration Once again, we apply that function we get the result and so on and so forth until we have our winner we found the cutest squirrel in the list and All of that was done for you the traversal of the list the reused of the previous iteration result and all that the only thing
You need to do is say oh if you give me two swirls. I can tell you which one is the cutest Which is what you want to express that actually what matters to you? Not the traversal of a list not the computation of a result So let's take a really concrete with code example I want to calculate the total of a basket so you have a shopping app you have a basket with a collection of items
And you're in your ui and you need to display something at the end. That's the total What do you do do you have it stored somewhere? And then every single time you need to you need to recompute it you can do you also could can compute it on the Fly no matter which way you choose you're going to have to compute it at one point
So the way you would do it normally is to say I have a collection of items Which is my basket, and I have an item which is a string and a price I'm interested in a price here, and you could do it like this You could say I'm going to initialize my total at zero I'm going to do a for loop for all the items in my basket and for each item
I take the total I sum it to the next price. I update the total value and at the end. I return the total But this is a lot of boilerplate because the only thing that actually matters is this right? That's what you're doing. You're doing a sum over everything so we can represent it like this using the fold and
Yes, fold is not something you're familiar with but if you look at it The only thing that is expressed here is I have my initial value, and I have how I process each item for each item The next iteration is going to be the total plus the item
It's the exact same thing like it's the exact same processing But in here, I only focus on what I want to achieve not how I want to achieve it So right now you might be saying oh my God is this is awesome I need to try that right now, but most likely you're going to be I'm super confused
This is a lot to take and it's fine. It's perfectly normal. This is a lot of things It's a huge world, and you don't need to do everything at once Don't do everything at once. It's way too much So let's keep things simple. Let's start small Today tomorrow when you start working again, you can start by making things immutable
Take the values that you process all the time take the thing that matter the most in your model and make those immutable It's a simple change, and it will make wonders for the predictability and understanding of your code secondly Aim for pure functions Obviously everything is not going to be pure function, but if you're doing something that is
Dealing with your models that you just made immutable Let's try and avoid side effects if you can push back maybe logging slightly outside a sec function or in Example of the user if I can create my user outside of the way of getting it. It's already a big win
So if you have to create something that is non-predictable ask yourself do I need to do this here or can I push it? outside and mainly keep in mind Focus on what you want to achieve not how you want to achieve it And if you keep that in mind it will help you break things down and understand more clearly how you should represent things
keep learning You start small and then you just keep learning new things keep experimenting learn a functional language It doesn't need to be something you'll be using in your day-to-day job it's probably not going to be something you're going to use any day-to-day job for me this was Haskell and
I really think it's a brilliant language to help you understand concepts because it's actually forcing you to use them And it's going to challenge you to think differently solve problems differently and by having that mental challenge While you do it. It's going to make it easier for you to break things down in your day-to-day job
You're going to see a problem and be oh yeah, this is actually three smaller problems, and I can break it down like this So learn a functional language But do it on a pet project doing on something you like something you enjoy the main thing you want to do is have fun You want to enjoy what you're doing because that's the best way to learn if you find something you enjoy doing and you apply some
functional principles You're going to remember those Because that was the thing you did on that really fun project not something you had to do in that really dreadful thing That lasted for three months, and you were really really tired of it, and you wanted to do something else so Keep those principles in mind try it and you'll get more comfortable at one point
You'll just be owning it and bring it to people around you so dive in Get some reads read some books around it. It's really brilliant. I have a few recommendations Learn your Haskell for great goods. It's a brilliant book to start learning functional programming
It takes things like from the beginning really simple and and build it up slowly You can take all the time you want to just take the book Take a computer and start playing around with it that book is actually free online There's a downloadable EPUB and PDF as well, and you can obviously buy it to support the author
But what I mean is it's not a big gap you can try tonight if you want to just like take the book read It and start doing the first pages. It's simple a Functional programming in Java this is a book that was written around Java 8, but as I mentioned it's not about the language it's about those principles and
You can learn from those principles in Java 8 and bring that to other versions or who knows maybe when we'll have Java 8 in Android right and Last but not least category theory for programmers. It's actually a book that is being written right now it's a collection of blog posts that are available online and
It's a bit on a more advanced side of things, so it's probably the last one you want to check out But it's really interesting in a way Where the author is presenting some functional concepts that come from the Haskell language, and then showing you in C++ How you could do it? And really drawing the parallel between math Haskell and C++ and showing you that it's not about the language
It's all about the concept and the way you approach things So here it is. Do you have any questions? Thank you, Benjamin?