Functional Programming with Java 8

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

This gets me excited, but only because I know functional programming more than object oriented

👍︎︎ 2 👤︎︎ u/[deleted] 📅︎︎ May 26 2015 🗫︎ replies

After using Java for 15 years (since version 1.3) I wonder how much version 8 will change what is considered idiomatic Java. In many of the examples I have seen people use lambdas and streams "just because" and not because it makes sense. But there are so many of them that I am curious about what their impact will be.

I consider anything version 8 added to be nice syntactic sugar and in the right situation very convenient. But the way people talk about these changes makes it seem Java became a whole new language, which I just don't see. Lambdas are great if they contain one or two lines, streams are a nice way to remove a lot of nested loops. That's a level of excitement I can understand. I guess it's just part of my inability to understand what's so great about functional programming.

👍︎︎ 1 👤︎︎ u/BiberButzemann 📅︎︎ May 26 2015 🗫︎ replies
Captions
well pleasure to be here and talking about some fun stuff that we all are excited about with the new release of Java 8 Java 8 has brought to the world the remains of most every reasonable mainstream programming language now supports a functional style of programming so I think it's a very exciting time to be in programming all over again so we want to talk a little bit about a functional style of programming so the first question I would start out with why care I mean we've been doing programming for a very long time what's what's really exciting about functional programming and I want to kind of outline first of all things when we write code what we're doing is we really are communicating we're communicating with fellow human beings were as passionate about programming as we are but really need to develop applications that are maintainable so one of the really important things about function programming in my opinion is it really gives an opportunity for us to be very highly expressive and convey the intent very quickly let's look at one example here let's say I want to just find out something extremely simple commonly used to I want to know if some numbers are primes so I'm going to say YZ Prime and let's just say a few numbers we know about 1/2 and then maybe 3 and 4 and I want to know if these are prime numbers so how are we normally used to writing this we would normally start out by saying given a number we would say well the number is prime if it's not divisible by any number between 2 and 1 less than the number in other words it's only divisible by 1 and the number itself so normally what we end up doing is we would start with an iteration off the bat and then we would say something along the lines of let's iterate through the number and starting with the two of course and then we would say well if we find out while we iterate through this that the number actually is divisible by the you know indexed we would then say this is not we would then say returned that the number actually we are looking at is greater than one because by definition one is not a prime number so so here is an imperative style of programming and I can see the result is false true true and false so that seems to have done the job fairly well we could write more tests around it but the point is what if we just do here we started by focusing on the iteration and that's where the problem is in us trying to write code we end up focusing on the infrastructure we'd end up focusing on the implementation rather than keeping the focus on the essence of what we're trying to do hi Sara morning so we could do this in a much more effective way by focusing on the problem rather than the looping so we could for example say first of all return that the number we have on our hand is greater than one first of all right if one if it's not greater than one it's not fine and then we could say well why don't we just say integer stream which is part of Java 8 and then we will get a range of numbers so range from number two to to number minus one that's a close to range and then we can use Oh none matches the given index value off the bat we could say that the number given to us is not divisible by the index so what we did here is we took the focus away from the looping and the code begins to read more like the problem statement so is it a prime number well it's a prime if it's greater than one and if none matches in this range of numbers that we don't have disability in this range so that's one of the biggest essence of functional programming is that it's decorative rather than being imperative we don't end up telling it telling it not only what to do but how to do it but we focus on just saying what to do and let the code deal with how to do it the difference may be small syntactically but it's enormous semantically because now we have the option of deciding how these operations of performed now if you really fund them if you think about it if you take any collection of values and send it to a for loop that is pretty static before does exactly what we tell it to do in this case sequential looping but we have polymorphism on our hand when we use functions like a range and none match because we're not telling how to do it we're just telling it what to do this could be done sequentially if you want to convert this into parallel maybe because the numbers is a very large number we don't want to compute them sequentially turning this code into a parallel loop is enormous ly simple compared to the sequential approach and the imperative style of code though we are used to writing so so that's kind of where we are with the functional style of programming so what does that mean to us from the point of view of programming it allows us to be more highly expressive we are able to focus on the essence well at the ceremony so there are two things I would say about imperative style of programming and one is saying how right and the other smell is mutability so we all know that mutability is evil but yet we have done that quite often now what what's wrong with mutability the minute we have mutability in our code we have to make sure we don't change it inappropriately we have too many moving parts in our code all right here is an example we focused on iteration we this is a very familiar code but complex because we got to start the IV value at 2 and then we have to make sure that the value is incremented properly you got to send the bounds properly so you're focused on too many moving parts here and the more moving parts we have in code the more errors are in the code as well so mutability often leads to more bugs not only that with mutability it's hard to make the code concurrent as well so in the case of declarative style of programming we focus more on in the case of declarative we focus more on not how but what we want to do and we avoid mutability be favored immutability and these two are really powerful we can write declarative code outside of function of style but function of style is decorated so that that is the benefit is we do more literary programming we do functional style programming and that is enormous beneficial I think so given all of this where do we go from here Java 8 has introduced some really phenomenal capabilities and by e-sens we can start utilizing some of the most powerful capabilities expressiveness as I mentioned about that so let's think about this problem we just talked about let's actually continue a little further on this if you look at the East Prime we already made it concise but I think we can go a little bit step further with this and this is where some of the real fun in programming comes about we want to make the code expressives look at this for a minute that's something we're going to stare at for a second and say huh what's that doing and then to me if we spend any time staring at a piece of code we have not communicated properly I want the code to read like a story not like a puzzle we don't want to sit there and scratch our head wondering what the code is doing so notice what we could do here we could we could say for example let's say we have a method that we're writing and the method is going to be another boolean and I'm going to say a civil right so we could say he's divisible and we could create code and and that becomes expressive so we can pass some numbers to the is divisible and say can you find out if something is divisible by this particular value but in this case we want to be able to capture this number because that is the essence we have to pass here but we can do some really interesting things with expressiveness in code because all we are passing through non-match is a predicate it's going to tell us whether this code is matching this criteria or not so with land expressions we have things like lexical scoping normally powerful it allows us to capture a state so we could say for example create a predicate here and it's going to take an integer and I'm going to say is divisible and what I want to pass to this is a number a divisor if you will and then I could simply say return number that we have on our hand is divisible by the device or equal to zero now if you look at just this code that we have on our hand of course we're going to have the integer in this case we don't have to specify integer type inference will kick in great now if you look just this part over here for a second we clearly know what the divisor is that's a parameter coming in to this anonymous function lambda expression but what in the world is this number well this reaches out to the defining context and captures it that's where the lexical scoping comes in and with the lexical scoping given to us now we can simply replace this code with simply let's start in the beginning we can say given the index we're going to simply say is divisible by and then we could pass the index given to it and then we can say go ahead and execute that particular function that I have into that context and execute it so we can start to write more expressive code along the way and and that really favours a much better style of programming as we don't have to stare at the code and wonder what's really going on let's look at a couple of examples of this let's say we are interested in a small problem the other thing about imperative style is like I said it turns into a puzzle than a story and we begin to wonder so let's take a little problem you know find the Val double let's say off the first even number a greater than let's say 3 well that's a very simple problem find the double of a you know their first even number greater than 3 but how would I write this as a imperative style well we would first of all say result equal to 0 and then maybe I want output the result once I find it and we would start with the collection given to let's say the collection given to us is oh let's say values equals and then let's say arrays dot as lists and let's just assume these values to be the values we want to start with and let's say we want to go through these values I'll make just a small change here to make this a little bit more interesting so so in this case we got a bunch of value on our hand and what I would like to do is I want to find out if these the result so what wait what would I do I would iterate through and of course you don't want to go through the traditional iteration that's that's so old we could simply say in and element in values and and what we would do here as we would simply say if the element is greater than three first of all and if the element is divisible by two we would then say well I want to go ahead and say result equals element times two well but that's not enough we have to break out of this loop so notice again we're focused heavily on the mechanics of the looping at this point and that's where our effort is given the result is eight why is the result eight while the first even number greater than three is four and four times two is eight well but unfortunately something is wrong in this code and we don't even know what it is at this time until maybe a tester comes back one day and says well your code sucks and we say yeah I know my code sucks but tell me how it sucks today well the problem in this case is what if the gift well actually would even answer that let's go ahead and do this in a functional style using decorators style and see if the problem reveals itself so what is a value start stream so what is a stream a stream is a fancy iterator given in Java eight and I'm going to say given the stream I'm going to go ahead and ask the stream to perform a filter operation and the operation I want to perform here is given an element whatever element that's given to me tell me that element is greater than three then I asked him to filter one more time and this time I say given an element again tell me if the element is even and and then finally we say go ahead and find out for me a double of all the values given an element give me the double of all the values that are even in greater than three then we finally say find the first value for me from this collection and then get it for me right so what we did here is we used a very highly expressive decorated style of programming and and recently said given these values recently want to be able to uh you know go through and find this particular value we are looking for what what happens if we run this well if I run this example I did get the value eight but if I remove this get for a second stop uh steps earlier and try to run it it tells us something pretty intriguing here it said I won't give you a result I'll give you an optional eight and maybe we immediately are half of course because it's possible that the given set of values may not have any even number at all or may not have any number greater than three at all it may be empty collection who knows so notice how that problem is hidden in the imperative style we have to think through with what has that reveals it's a very easily in a more of a decorator style that is one of the things I really like about functional style of programming but we can go a step further from this to make it more expressive for example I can take this part of the code it is checking is greater than I am and I can simply say over here let's say static boolean and I don't mean to say that all methods are static but in this particular example given the context of the example so I can say is greater than three for example I could say number and then we could simply say over here well just return if the number is a greater than three right so we could say number is greater than three but what's the benefit of this the benefit is we can now come to this code and say the sampleclass is greater than three so now the code begins to become more expressive with this wonderful thing called the method references available in java 8 so similarly we could go away this could go away and we could simply say sample is even for example where the ease even could be a method we are implementing within this class and so we can say for example here a static again boolean and we could say is even again given a number on my hand I want to simply return if the number that I'm given is actually a even number so mod to gain equal to zero so we can begin to become more expressive in the code and now we can start reading the code what are we doing given a set of values filter out all the numbers greater than three then filter out all the even numbers and then double them we can input that method reference for it and then find me the first one so we can see how this becomes more and more expressive and the code begins to read like the problem statement so that that's kind of what is exciting to me what's what's your thought so uh Maine time um can you hear me okay yes absolutely yeah okay that's that's great and I think that one of the questions that many people have there is there is actually one question all that which I can ask you in a second but one of the questions that many people have you mentioned that you move towards a more decorative approach of um of writing code which is fantastic because it's more about saying your intentions as opposed to implementing your intentions and in the imperative approach and it's more about showing how to do it and the other benefit you were talking about it was in terms of concurrency and being able to you know in having immutability etc avoiding those types of for loops etc but under the covers a question is under the covers this is ultimately implemented in a specific way it's using those for loops etc so is one to assume that the library is taking care of all of those little details well that's that's a very important question to think about and the well couple of things we need to keep in mind right ultimately everything goes down to machine code but we don't want to be writing in machine code certainly we are working on higher levels of abstraction and almost every language we programming is turing-complete so but that doesn't mean that the there are no consequences the differences are enormous because when you are dealing with a filter and a map this is not the traditional form loop that we are used to because there is quite a bit of optimization that goes on in some of these implementations for example one of the biggest strengths we have on our hand here is notice we didn't send a result instead we provide a function to this function so this brings up in functional programming we use what are called higher-order functions so what that means is we can pass a function to a function which means that this function can either decide to evaluate this function now or it can evaluate it later or may not even evaluate it at all so in other words this leads to a powerful lazy evaluation if I really think about functional style of programming we talked about how does it feel to bite the code and we said it's decorative it is expressive it is something that we can just easily communicate but let's turn the question around and say what other benefit do we derive from it and to me there are two main to main gems of function programming looking at it from that point of view and one is lazy and the other is composition we only saw the composition here notice how this flows through and that becomes very expressive we go through a transformation of objects rather than mutation of objects but on the other hand the lazy valuation to me is probably one of the most powerful things this opens door for so many possibilities if we write the traditional for loop even internally for loops are normally eager evaluation they evaluate right away and to really make them lazy takes a lot more effort but the filter on this hand is actually lazy let's see actually how that is true in just one second with this example we just started out with so to understand how that works let's convert this just a little bit more and we will say here sample and we'll call it as double it and this is a really small example pardon me like the one that actually brings out the essence really well in my opinion so let's say we have a doublet which takes a number and as an argument and I'm going to simply return here let's say number times two well the result is great it produces but imagine we wrote the all four loop eagerly evaluating the result what would we do notice we have ten different input which means we're going to find if every one of them is greater than three so that's ten operations keep that in mind then we're going to see if anything greater than three is going to be even and that would be seven more values to be evaluated right there so sten plus seven is 17 operations doubling all the even numbers that's four six eight and ten that's four more so we have twenty-one operations to perform that seems like a lot of you know looping to do if we were doing this in a traditional four loop under each one of them but thankfully that's not the case so if you notice here I'm going to output here is greater than and I'm going to simply say here called for let's say three and then we're going to say a number that we used to call here so similarly here I'm going to output let's say ease even and then I'm going to specify number again so we can actually see this being called and then finally I'm going to output double it and then see if double it is being called here on the number and notice the surprise from the output we see now well it started out first of all in the output it asked if 1 is greater than 3 and then 2 and then 3 but then notice after 3 it went to 5 and once it examined 5 it said oh look fine is actually greater than through me I am going to go ahead and apply he's even operation on that value well 5 is not even forget that then then when goes to 4 and starts over with is greater than 4 4 does even for for doubles for hands it over the fine first and the 5 verses I'm so happy to thank you that's all I needed and everything shuts down after that and goes home it doesn't evaluate the rest of the values at all so what you seeing here is the effective laziness we just got for free by using the stream and so if this was purely a mapping over to traditional for loops under the hood we're not going to get these kinds of benefits so what lambda expressions do here the fact that these are functional and decorative give the expressiveness opens door for some beautiful optimization and so what Java 8 did here is it fused to these operations into one operation and in Java eight methods like filter and map are really called as intermediate operations and methods like fine first reduce and collect are called as terminal operations so these operations don't even execute while you are passing through and if I were to grab all of this into a single variable here for for a minute let's go ahead and put this here into one variable and save it here as just a you know let's call it as you know temp over here for them for a minute and and and if I evaluate this tent further and ask for a temp dot fine first over here and get the value well the result is going to be exactly the same as we did before but for a minute just remove this final face from here and run the code and notice the quietness that you want to see now because all these were lazy and they never really did any work until the terminal operation triggered its evaluation and says now can you go do minimum work for me and that is one optimization that this style opens door and shows that it's not a direct mapping over to the traditional form loop under the covers yeah that's absolutely very valuable to know I think and the emphasis there is that you're getting all of this for free as a side effect and so the beauty of if we write the code well there is so much improvement it can be made to it but if the code is shabby and mutability all over the compiler looks at this code and says I don't want to touch this stinking code with the 9 foot pole and it leaves it poorly optimized but when the code is it's it's kind of like what you would do right if I write a report really bad and give it to you to review you can find all the grammar errors in it but if I write it and spellcheck it make a good grammar revise it a few times maybe give it to a friend and look at it then I give it to you now you're going to talk about hey let's look at the content you have look at how you can improve this you can talk about this you can talk about that and we're going beyond these you know trivial checks let's find the bug here but bug there into really good optimization so it feels like we're giving a better quality code to the compiler and the compiler Pat's us on our back and rewards us with hey here's some optimizations can do for you for free so so better quality code results in better optimization and that is the lesson I've learned there looking at this I think yeah there's a there's a couple of questions Venkat if you wouldn't mind um the quickly answer because it's in the context of what you're showing there's one question from Dennis it says is the optional types type parameter still erased at runtime in Java eight the type I should still the problem so I really don't want to talk about genetics because the minute somebody mentions generics I get so angry I still am bitter about generics type II ratios but but the hope is that there's an option maybe eventually in the future we'll have good reification and that would get as a result but but yes unfortunately the type of a should still do kick in okay and there's another one that says can you replace is greater than and is even with lambda expressions which I think that originally was right yes so yeah absolutely so he can go back and forth with this you can say I don't want to have a method reference I would rather you know have given a value I would rather say he is greater than three you can certainly do that in fact in fact what you can do here is you can even say given the value II I want to say is greater than the value II and you can pass it down the chain like this if you wanted to and you can see that the result is still the same but but the beauty is the IDE now kind of not just you a little bit and says hey do you really want to keep that that way or do you want to replace that with method reference and then you can say yeah I want to opt out for that and then you can kind of opt-in and opt-out method references are really charming but but I have one advice about method references I'm a huge fan of the slogan and and my slogan is make make it work first and make it better real soon as we are getting used to Java 8 method references can be very intimidating and and my recommendation is don't fall into the pressure of making the code concise because what you may think as concise may actually be terse to somebody else reading it so go ahead and write the code with lambda expressions get comfortable with it and then if absolutely makes sense that a method reference can be used in sort of the lambda then go ahead and change it but but give time to get comfortable with it and and and if you use nice ideas like what we have here they can even prompt you to say hey this is a good candidate for use for method references but one of the rules of method references is if you look at this right here for a second notice we received a parameter and we simply pass the parameter to this function imagine for a minute we have to do a times two for example well if you do something like that didn't notice the ID doesn't prompt me to go use method reference anymore because it figured out that I there's actually a bit of intelligence in this code so method reference cannot be used here but if it's a simple pass through where what you have seen is what you send and I was thinking about this and I gave this a tap turn named for this when I was writing the book and I call this the office office space pattern remember the office space movie in that we have con and what do you do Tom well I take the requirements from the business people and give it to the programmers so this is like the office space pattern there's no intelligence at all happening and those are the cases a good candidates for conversion to method references because there's no intelligence going on in the code but but don't we shouldn't be you know eager to run towards them we should evolve the code and get comfortable before we use them so absolutely there's nothing wrong with using lambda expressions instead of method references until we get you know comfortable with it okay that's great right so I think in terms of questions let me just check there is a what there's one which says great but can we use it with the date I'm not sure if with the date as in the new date API or can we use today I'll follow up with that okay well let me actually answer both of those questions the data API absolutely where that also gives up quite a bit of fluency we can use it well we can use it today as in so I've got a couple of suggestions for that I was teaching a course on Java eight recently and one of the gentlemen said hey we are beginning to use two of eight but we are releasing libraries that are used by people still on Java 1.5 1.6 1.7 so what gives what can we do well the beauty is when you start designing your libraries for use with Java 8 use sams or single abstract method interfaces and when you start using single extract method interfaces those using Java seven or earlier can still send anonymous inner classes to their code and those using Java 8 can send lambda expressions and depending on how they compile the compiler will essentially determine whether to use invoke dynamic under the hood or to use the regular anonymous inner classes so you would like to read that use a single abstract method becomes quite viable easy to use in different versions of Java and it's very easy to see this property really strong so absolutely we can start designing API today even if we are programming in Java 7 or 6 but start designing with simple abstract method interfaces so when we do an app doll at 8 the transition becomes simpler and then also if you use IDE s which are really good at recognizing these smells they would look at your code and say hey look this code can be easily converted to a lambda expression and then as you start using Java 8 on the projects it can do conversions for you and and reduce the amount of code as well so absolutely that there's a lot of power to is to think about you know how we can design with that okay um the Thomas that previously asked the question about can we can we replace greater than and is even with lambda expression he clears it up by saying that what he actually meant is whether you can assign the lambda expression to a variable what type is is greater than that you got you so so if I have an e and that's a wonderful thing to think about there are there not too many times that you would want to do but but let me say one reason why you definitely want to do I'm a huge fan of good design and one of the things we should absolutely avoid at any cost is duplication of code so imagine if we're going to have this lambda expression e greater than 3 and for whatever reason let's say we have to use it again maybe down below in another expression and we're going to use that in another expression below now we have duplicated that logic and that is pure evil to duplicate code like that so what we want to do to avoid that is we would say well first of all what does a filter really take what a filter takes a predicate it's very easy to see that you can look at the prior filter and say Oh filter takes a predicate I understand what that's taking and what's a predicate a pretty good as a Sam a single abstract in method interface and and predicate itself has a test method so if you look at predicate itself you will notice it simply has a method called test so that gives a context to what we are dealing with so at the other in the sense a filter is just accepting a predicate so what we can do here is we can simply say give me a predicate which takes an integer and and I can say is greater than 3 in fact I highly recommend this and the reason I recommend it is you don't want to write static methods and pollute your class for the logic you need instead it's nice to create a function within a function itself using the lambdas so here I'm going to say given a number I want to return if the number is greater than 3 and now I can simply replace this with the sweet is greater than 3 and ask you to do the work so of course you probably want to give the good name here is a greater than so greater than 3 and you can do something along these lines and then you can say it but look at the beauty of thirds you can do this sure but you can go even step further what if you really wanted is greater than 4 later on and greater than 5 later then later on you don't want to duplicate this code duplication is fundamentally evil and we should illuminate it as much as we can within reasons of course but what can we do well here's an idea rather than doing this let's go ahead and create our function for a minute this function takes an integer but it returns a predicate off an integer no that's a little bit you know intense but to begin with but once you get a hang of it you would love it so is greater than and what does this do this is a function and this function says give me a you know a pivot for example and what I'm full of returned to you is a number given me a number the number is greater than the pivot so if you look at this code what we just did here is we created a function called is greater than which takes a pivot value but returns a predicate that tells me if the given number at that time is greater than the given pivot again lambda expressions can capture the context in this lexical scoping so now I can simply say is greater than and then I can pass a three to this function right here as an applied call so apply is a function of function and so we can say is greater than apply three so this is a eager evaluation that returns a predicate that we saw here and that predicate which is really this one that we're returning with a three but later on if we don't want a three and user four we completely reuse this piece of code rather than duplicating it so this is the beauty of this I really like the question that was asked because this shows us how we can end up removing duplication in code and have these as little building blocks but let's take this one other step if you will you can now wrap this into a utility class and rather than utility classes giving you functions that return results you're currently classes now can have functions that give you functions so that's the difference between giving somebody a fish and giving somebody a fishing lesson you generate functions that can be used over and over on the receiving end rather than giving a function that will only return a result when called upon and this gives a lot of effort ability to customize and generalize code much more effectively so this is very exciting way to think about it in your opinion so so this is actually does this leads to another question because the you talk about composition of functions right here what we're doing is basically we have now in your case we have a main function inside that main function we're composing it up another function and it's like that this filter which is taking is greater than when it comes to I mean traditional models of object orientation where you have for example a class and you have this you know a typical class that talks to a database and then we've learned about dependency injection and how we can pass in the dependencies and change the behavior during the test etc how do we approach that in this functional way how we oh that's a fantastic question and yeah it's a fantastic question and I think the reason why fantastic is it really hits the nerve of the possibility here you know in a great way we have injected dependency injection right here in the code to filter because what you're telling is we're telling the filter hey your job is to filter the values in this collection but I am going to give you the details of filtering in a lazy manner later on and and so if you really think about it what is dependency injection fundamentally step by step for backward for a minute and look at what does it mean dependency injection it is nothing but a very glamorous way of thinking about the strategy pattern right because we are saying I've got a scrap different variations of strategies I want to write a code in a general way so that I can inject the strategy as dependency during the code execution time this is exactly what we are doing so in dependency injection is is essentially a strategy pattern you don't have to use dependency injection only an object with reprogramming it in a sense this is extremely powerful because if you really think about it let's go to some sort of a simpler example to think about how the dependency injection plays a role in in a slightly different context let's say for a minute we're going to write a function to you know take these values and total them so we could say for example over here you know int total values and are we going to give a list of integers let's say numbers over here we'll call it numbers and all I want to do is just total these values out so we could say for example numbers let's take a pick up in your traditional imperative style we can convert this to a decorate is fine in a minute so I'm going to return the result over here but we could say for in element in numbers and we could then say given all these number values I want to simply total the result so the salt is plus equal to the element but rather than totaling all the values if I really wanted to total let's say only a select values what are the Select values I don't know I can decide that later I won't be able to vary that so what we normally do is we would create an interface here maybe we'll call it as a select or and we would say the selector is going to be passed in and what would we do as a selector well in Java we are used to creating an interface called a selector interface and then we would specify in this interface a public you know let's say boolean let's say pick and then we would say integer value and we would then leave out and say hey that's an interface we will implement it later then we would say class even selector and then this would be implementing the selector this is called ceremony and we have been led to this in Auto programming quite a bit isn't it and then here we would say if the value is even so we would say mod equal to zero then accept it but all this is a fluff because we are forcing a vs. to implement objects but what are we really interested the essential part right is this part right here what is all of this this is called the ceremony ceremony is what we have to do before we get to do what we really want to do and we have entertained ourselves with all the ceremony so we could get to this fun part of writing that expressive code let's see how are we going to do this now let's keep the selector for a minute let's not throw that out let's keep the selector for a minute subscreen a selector and I'm going to come here and say if these selectors uh is going to have a pick method if it picks the element then I want to add the result not otherwise so we still did what we did in all programming we still what we did in Java we haven't done anything very differently however when we come to call it we say given an element simply return a true for me please because I want to total all the values so in other words rather than creating a class we end up focusing on the essence which is the function we want to perform so right there is a dependency injection because to me a dependency injection is nothing but a strategy pattern and that's what we are applying here so this selector became a strategy but of course we don't have to go through that much effort because this is already big ten we can turn this into a thread kid for example and then we can say that takes an integer and now we can say well that's going to be just a test function we can run through that now and and now similarly we can say total values and then give the values and say given an element tell me element is even and we can say only total even numbers and not anything else and now quickly we can say all right know that we are performing those two operations well it's actually output the values is to you know see it here and when we can see in this case now that we have the result of this let's make this e is going to be even and and we can turn that around to more of a decorative style very easily by simply saying why all this fluff again simply say that I want to take the numbers given to me well returned numbers again I am given these numbers I want to simply say get me the stream and from the stream I want to filter out only the values that I want to select and can suite we can just send the selector to it and then we can say then say you know reduce these values starting with the value of zero and one perform a sum so we can simply say a math dart you know exact add exact and ask you to perform that operation on it and we can see that the result is 255 and 30 so we can again make the code very expressive but that became you were dependent the injection so depending on what you're doing you're still passing an object so you're still doing exactly what you did in Java except on the calling side we don't have the ceremony of a class we can nothing stops us from creating an anonymous inner class and sending it our refer to an existing class with this method but this becomes a lot lightweight we're able to focus on the function rather than the class that we have to build so so the beauty here is we get this benefit of mixing object composition along with function composition as well so this is you know a mixture of the two that we can enjoy but rather than being restricted to one or the other and I think that is the that is a benefit moving forward that's great and we've got quite a few questions but before moving on to the attending questions are there are two other questions that we want to discuss it is there apart from the lazy evaluation that you've spoken about is there any more two streams that we should know for example you know hours or etc so what are the biggest benefits of screams itself is streams is like this magic that that happens with with the enormous amount of beauty and power to us so for example let's take a very trivial example here let's say I have a list of values that I want to start with and this could be anything we do depending on the computation we perform and let's say equal to you know a list of numbers we have on our hand and given these values let's say I want to double eat the values and total them now this could be stock prices coming in this could be other values we deal with who knows what these values are and I'm going to say over here well how do I you know go about totaling these values a double of these values well we could say number start scream and then we could say for example dark we could perform an app operation map is a transformation so given an element we would say let's go ahead and say sample a double it and I want to double the values and then when I'm done with that I'm going to actually in this case say map to end because then I can simply use the sum operation on it to perform the double operation so we can see this now what does this double it that I'm going to use here as a method reference well let's go ahead and say this is going to be a method which is mayor let's make this a static with it as well it's going to give us a double it value right so double it and this takes the number and returns let's say it number times two still return number times defect just this hypothetical example imagine for some reason this is a very slow operation so I could say for example thread darts leave and maybe this has to go to a web servers get some data do whatever that it has to do to perform this operation and so I'm going through this and and working through imagine if we had written C is sequential using a for loop I won't write the loop here but what is it for in element E and it would have worked in the for group so we could have written it using the traditional style as well to perform this operation so if I go back and run this little example that is going to double the values and some it we can see that it's taking some time to run and how much time it's going to take well a little bit more than a 6 seconds delay and gives us the result so you can see the feel the delay in there that was about a 6 second delay but the beauty is we thought perform the functional hygiene if you look look at this method sample it is pure function what is a pure function a pure function is a function that has no side effects it takes an input and it gives an output so one benefit of a pure function is it's easier to test it because as long as we keep sending exactly the same input over and over and over it gives the same output all the time so writing tests on it is very tricky you know completely writing the test where durability is happening in the code so the point really is this is a pure function when you have a pure function we have what is called referential transparency so what is referential transparency a referential transparency is where the compiler can replace the method with the result of the method if the input is going to be the same so if you call double it and send me a forward no matter how many times you call double it with the for the result is going to be always an 8 so I could replace a double eight parenthesis for after a first call with the value 8 and no no no longer have to incur the overhead of calling it not only that when we have that social crash currency we can rearrange the code quite optimally for performance reasons but one benefit of that is the stream can say hey look when I'm evaluating this I'm sequential evaluating these values one by one by one and that's taking really long time six seconds is eternity for a lot of us and it gave the result but let's just simply say parallel stream a rather than a stream and and we just kind of put it in a turtle ward with one flip of a switch and notice this time the result came back in about a second rather than six seconds so this was a very large collection now here's what I get really annoyed when people talk about performance without context if performance is really important let's revisit that for a second is the number of input is really small you don't gain great performance one over the other it's generally a wash if your input size is very very large your real performance gain doesn't come from running the sequence should go a little faster it is like going to somebody who's bicycling and saying bicycle faster pedal faster pedal faster if you really want to go to a different place within a matter of magnitudes of speed you don't ask somebody to pedal faster you go get an airplane on a rocket on a car depending on the distance you are traveling in a similar way if I have a very large collection and I really need good performance what I really need to do is to off do multi-threading well the problem with multi-threading is the minute we pick the for loop the traditional for loop and we touch it to make it multi-threaded the code no longer looks like the code me once rode it has turned into a monster and and so what does concurrency mean people start messing with the code try to fix the bugs they introduced and they updated resuming right away and concurrently apply for another job because the code has become a monster well that should not be what concurrency is so the point really is we should be able to go from a sequential code to a concurrent code in cases where we can without expending so much effort notice that's taking about six seconds to run but because we maintain functional hygiene the stream says not only can it run in a lazy mode I can also run parallel if you just want me to so we still control the switch but it goes into a turbo mode when we flip the switch and that opens the door for the kind of optimization very easily because of the decorative nature because of immutability being honored and I think that's very powerful a tool on our hands as programmers that's awesome um so and how is this like because you know for the past years I mean Eric Meyer with Olaf used to work for Microsoft and he came up he you know worked on the reactive extensions and now that's become part of the Java space rx Java and Netflix has been doing that so how does this all fit in with reactive programming I mean it is there any like does one replace the other is that you use them together how is it related that's wonderful question and and what's really exciting is you know when I looked at where I put reactive programming it is as if like looking at this like of course was the reaction when I looked at reactive programming so take take what we did so far here we we addressed very two very important capabilities here one is the expressiveness and the other is the lazy evaluation and the third of course if I bought my Runner and the third one here is of course the ability to paralyze these things but but there's a couple of problems on our hand we look at parallelization well because laziness is awesome great paralyzation is awesome that's great but what's going to happen if for some reason the function you are calling here were to throw an exception let's say you are going to a web service and ask them for some data from the web service and that data doesn't exist and it's going to give you an error and you want to propagate that as an exception if you're doing the sequential e you can handle the exception right away but if you're doing this concurrently multiple threads are running one of them bomb how do you know things actually fail so take reactive programming as a higher level of abstraction where do programming takes bits and pieces that's available in front of it and raises the level of abstraction the first one is lazy evaluation you want a client and a server parts working with each other but you are really producing results and the consumer is consuming it but you only produce results as and when the consumer wants it so think of this as an observer pattern with a few things added to it the lazy evaluation able to communicate back when a termination happens from the server side ability for the client to tell the server thank you but no thanks don't evaluate any more so since you're evaluating lazily you can evaluate only on demand as a result you're not eagerly evaluating and wasting resources and all this gets added up so think of reactive programming as ability do lazy evaluation ability to communicate a good observer between client and server about interaction terminations and also lazy evaluation add on top of it the resilience part where when one of the components end up failing that exception is propagated through a very clear abstraction so the receiver can actually handle the error and then can say now that I got this error I no longer want to do anything more or you know ignore this error I've handled this on my side let's pretend that we have more work to do please give me more data that kind of abstraction can happen so so reactive programming is you could say functional programming plus plus where you are taking the lazy evaluation the parallel streams and so when you're so cuckoo like your question how would you build this when I program in reactive applications are you streams are use the laziness of stream but under the hood inside of the reactive API so the reactive API gives me the abstraction to provide the observer mechanism but on the server side I use the stream for porting that laziness of evaluation and then reactive API tells me whether to evaluate the next element or you know give up and say this is done or communicate back to the client to say I'm done with my processing you know go do something else or tell me what else to do so that is higher built on top of functional programming you cannot imagine doing reactive programming without the capabilities that function programming has offered like the laziness the purity the referential transparency all those wonderful things add together to provide reactiveness so this is a perfect storm where all of these coming together to a higher level of abstraction very exciting way to look at it I think yeah so we have got about four more minutes mainecat and there's a ton of questions I'm going to try and go through some of the important ones or those to repeat and then we can see if we could follow up with some of the other ones later on one of the questions is there are questions here in terms of you know what are the benefits of me using Java 8 if I'm already using a Scala for an instance and I I don't think that we could really get into these types of questions with a few minutes we have left I don't know if later on you want to maybe follow up with that but there is a question of should I be using Java 8 right now for new projects in production so something to quickly address both of those events but the second question is yes you should and the reason is the sooner we start using it thus to where we became the experience for it and and it's been around for a long time you know people have tested it I've seen the interaction on the mailing list so absolutely go ahead using it and to quickly say the Scala versus Java is it's not one versus the other now that we have this available in all the languages interoperability becomes really easy Scala will benefit because of invokedynamic as well and we can interoperate a lot more so if you're only using Scala that's great there's nothing wrong with that continue to use it but if you're going to have it with with Java code you can also benefit this on the Java side as well and of course you can begin to start using a better interpreter between the languages so I don't think it is as a one versus the other we can benefit from learning from both both options and see which one is better and pick the one that makes sense okay and I think with just the last question is is it possible to use carrying or partial function applications with Java 8 I'm so cutting is something that's very easy to build for ourselves so for example really quickly you can say I want to take a lambda expression like let's say we wrote a predicate so we could say predicate Curie and then what does Curie really mean so what you can do is you can write yourself a little cutting function right so you're cutting function would say some input let's say integer value and then within this what you can do is you can say return you're going to return some function let's say function and whatever function you want to return which takes zero for example you simply say in this case is I'm going to take one parameter you better salt but the other parameter I intend to take is the value coming from here so you would use that value with the newer expression so in other words cutting is nothing but a nice little use of lexical scoping to capture one value so that you can use that value in creation of another function partially applied functions are lot more difficult because the language would have to support that a fundamentally in Java it doesn't do that but cutting is not hard at all it's great venkat I think we're out of time so let me just switch over second who's on so so first of all before I continue I want to thank you very very much Bank up for this awesome webinar it was it was really great I really enjoyed it and I and we I think that we had a very high attendance and I think people in general have very much enjoyed it unfortunately we haven't had time to get to all of the questions so we'll see what we can do about that later on so thanks again once Venkat for for taking part in this appreciated for more information from us if the feedback in terms of if you want to get in touch with Venkat please email Venkat as agile developer calm or on his Twitter handle understand Venkat underscore s in terms of us for more information about upcoming blogs or sorry webinars or features of some of the things of Java aid that we support and IntelliJ please visit our IntelliJ calm sorry Japanese calm slash idea web site as well as the blog and Joe brains TV where we'll be publishing including this webinar and if you want to learn more please follow us on JetBrains and IntelliJ and then cat again once again thank you so much and thank you everyone for taking part and we will be publishing the recording very soon and see you next time so thanks again
Info
Channel: JetBrainsTV
Views: 229,470
Rating: undefined out of 5
Keywords: IntelliJ IDEA (Software), JavaScript (Programming Language), Java8, Functional Programming (Programming Language Paradigm), funct, Venkat Subramaniam, Software (Industry), JetBrains, JB_IDEs
Id: Ee5t_EGjv0A
Channel Id: undefined
Length: 58min 23sec (3503 seconds)
Published: Thu Mar 27 2014
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.