Functional Design Patterns with Java 8

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
ciao sono Matteo uno de coordinator Adele joke Milano blow Pilate bereavement initiative importante Antiqua Stano kamioka-san pinata doll support oav oxidized Milano no conference Adele chiku today Vox organic that Otisville pottery paratrooper Tory can invent event Eterna Milano analyst was seconded its own McGarry encuesta Johnny D Festus tied up in Santa pian if acondo confer a little anova quindi echo not emo propósito a quistis will be don't be led to perv oxidase Milano with I compete college a stoma kadar Grundy fruit in a Lenovo a profit on a tsuba topical early bird as kadhi a brave a quindi box eight days calm the lash Milan Turin Linda concerning squid so topper to telling formats eonni a Queen d2 video ma preska venuti are link control numero miss an emetic attach interested rabbit Sarah's printed movie Natale sitting Tong Kikuchi from molto piacere abbiamo only lustrous Peter questa Sarah a gentle a sponsor k comedy trunk a procure Otto pizza bee bee tee bee rapaera hospital to digitally to bury me in tilapia Luca the raccoon town a timid of Asiana the moon braving tradición a fellow sponsor a parole sponsor operate immediately told no V robots removing yes M VistaVision all three all three all three speechless bravi bravi bravi so Rhonda Kizuna question on Nova tomorrow questa you should mukha for to programa Toriko see me throught the internet at the swiss people goes ask those paths you okay uncle king to feature dimples in the throw la prima Givenchy Tameka my husband and me to see technology Kunak Winnebago ultra me come on all aboard Isola Dvorak owned a partner only questioning mr. solo for math technology years BG Dvorak we educational design yeah UNITA human Domino mica my Jackie link me a fan o digital marketing amon tobin Ali import eve of Dumbo D&E and this is d5 a para una cosa visto que la serie l weekend alluro fission Lozano sukhasana wish no community Emiliano típicamente tech business to see me one day to psychosis Tecate superior mo mo more efficient for mcgrath muita packet antonova Cyril weekend no Luciano in questa activated I support a semi tank attack ready makino an intermediary collagen they give you death no love or a quit intro Alan's in the perk you lavoro yo I belong me in TECO safar me permit the nominal community windy press DramaFever a support receive a statue Piazza a passo di g / fortuna park a no soda so last Aquila communities if I may say so no Anki Maura David me come I Francesca kidding me oh so - Leo come siempre see a Chaba catchy piace ma ma de bourree Francesco sicker I mean telegenic off from low spots you Inori Tony visibility to the representacion a the vero a la Vega busting Zapata visibility' Laurent no cuesta resource la Sierra say no Dada no disposition totalmente ricotta Queenie psychos je te amo deport on película de dar una mano last light during returning to pare yoga in the taurine perky since during the tour in soma even TC - Padre Brava medalta unki super to the participant Eber KS Ottoman territory 7g Fausto participant ele in this I know see Petrovic in the grass the grass Tecate m : conformity on a minute all the community put the disc really a queen novita new Delta non tanto percale August now molto Khun khrap blog Punta Mita Budokan put a today there a lolly study proximity cone post purchase Kahuna very discreetly on a mink Aldous Chrissy owned a deli window a photo present at the FASTA pasta per Ola bike by Mario let's see this revenue D números eval Ultimo in control of doom in addition Nova Thank You Victor for coming and see me Oliver did we so Louis MO continued on the wall of granite the C&L box eight days queer Milano Sara I said if you magic over sujud 804 paper paper of oxidized Milano is open so I invite you of course to participate if you want thank you I invite you all of you of course envy the party for a logoff reversibility automaton to or ability Alberti beretta so nobody underscores windy London ovarian early bird the thinking over public other program finish and I constitute a team across a cocoon Adela was transient was interesting there's other sponsor it's our metadivine conduct ovum a turkey Modica become a posthumous efficient Kratz I mean what's today - ah softer benissimo which remain the Swiss theories managed not to mention variation in particular Nostra tema Co copa de la capacity optimization rajim o una cristo Ogawa so business case okay delivery ammos - for my product e so thomas our second brain geometry elixir to form on premise mulatto variant called brain through sight microcephalic capacity means issue in general a capacity mediation and also on mercy - Gemayel apart edition with satirical informatica reaper diamond he kosovo say the teleportal far a performance evaluation a capacity planning at universe implement server farm Wendy said vividly mention our system in format weendigo Safari so with no softer Co let's see another system in format we need database rage Network big data so on a t-shape condition a uterine in question is a traditional server farm of the cloud ultimate Darla was root we needed okay Oh moon Quebec a survivor additional just additional two twisty server a Christian knows to determine not strictly entries in the Pureland deployment program The Gambia a just Jean Christine Marie just an illusion Tamila Cervera we're che do diversion community ruin just the Giorno we need someone on the new Mary peligro see Christopher a monocular to the Mentalist Acala a you know so team the Shamu a audiences from a milano pero a unconditional in America in India she's not risk ram in Italy she commented e-marketing new UX and support quistis one of the colleges will give interest in general but apart the backend Vinci one mentor Java Java tapenade loora loora agenda Jolanda Chapelle apart and Papa Nova in common framework live demo spring WebM embody spring cloud the Queen Dean reborn a zookeeper the contributor party from 10 the memo angularjs fell apart anova angular ATO a para partition the deployment of vehement promises you know mr. Ranger Elmo let the closure by true to you to meet remains evil just rephrase also second ecology daddy taught work so no GPS cough hold the microphone 10 the continuous can finish i'ma bust and Sudha Sharma system evolved a endow the Somali in with ecology in Australasia demo abbastanza contrabass stencil tree ninja be a photo oh gee primo journalism in ghana victor de que la parola hi hi everyone good to be here first time in Milano for business purposes so this all this stuff and also to learn to play of course good so functional design patterns with this list what they say so this time should be talking about so let's start slow with something really easy how many of you are using Java it but many I mean really using Java weird things today right first things first let's first define this method let's say public let's return the list of user of a user DTO did you know because they did the transfer object and I will say get all users or you send and I will say I will need here user repo user repo right this user repo let's make it as field of type user read prospers use the repo is rapper and then the spring t mode will cry and say okay where is final here good make a constructor even better why not let's do this right normal constructor for us long book the constructor is even bytecode but not in code hidden for us is nice and easy and use a report dot finder and then on what it returns you this if you are curious this returns your list of users now on this list I will need to do further of for expected for and iterate over all users now for each time I will instantiate a new user DTE oh good and make it a variable name DT or very wisely and then DT no dot set username taking directly from the user get username and then DT yo D key o dot set full name and then follow mr. key because I have to concatenate user gets first name + space you know the drill right we've all done that from years and years the user that get last name upper case upper case the game named code golf the name name the game name code goes goes like this who solves the problem in list keystrokes you dot get last name enter upper just in five keystrokes and then okay to end this statement which is not yet come up even if it's not complete to end the statement control shift enter and finishes completely and then DT as ever hours only clips sure I wasn't equipped for thirteen years I switched intelligence that set active and then a user dot this active in case the deactivation that is moon right and then I need to add to the to a list of details uh so details that add this this this new DTO good but who is this I took it a local variable not arrested a list of user Det which of course needs to be outside of the list and this is Java 7 style equals new and then its new ArrayList good and at the end return details look this is the code that you write over and over again in our enterprise information systems this is a disguise for saying stupid bull not bullet I get the part and you type this over and over again in all sorts of situations the same idiomatic first then the principle is not to repeaters that's not only the code a literal code but this style of coding so then you would like to extract because this will always have a list of it here he will already trait over the list you were always add to the list and returned a list so we will extract only what is what is what is special about this which is this part and you make a method out of this and you name is very wise to to DT know of a user right good in which case this is useless did this variable I would inline the variable you get the point I am a refactoring maniac and the people that I've done today with they know that and then click on the for you don't know little you can do collect again for collect it replaces everything for me just niceties this random homework for tomorrow click randomly in code and press alt enter see what happens it's really you don't have to just do it okay and this is the useless this variable it's yellow because it can be inlined so in but now this is one interesting way of doing things but of course you you could you could let me just inline this all but this is bad my friends you should do so folks if I select this token and I press control shift F meaning find everywhere but let me try there should be zero matches you should never find this token in your code base what this token is actually a poor so an anonymous function crying for a name it just very sad it's batch of code without without a head it's logic with other head imagine a function what don't you don't have to think just extract everything ctrl W so the whole block take it out to be here very nicely and then of course if you write this intelligible say you know Java is too much this and actually even more you can replace it method reference good but every now and then this con transformation is so easy that you can actually actually the key points here is that you don't need any external service to do the conversion based on the data of the user you will create the user detail so what can you do you could say return new user DTO of a user and pushed all the conversion inside the constructor of that DTO let me try to do that so it's red when it's red yellow blue or grey our printer will fail your day that's the spiritual sense this is page clean third look I have so I'll enter if it's red yellow blue or grey alt enter will save your day now to be to be able to be correct politically I will add these two also for those of you so it's if it's red the other need to think don't think when it's red you just are tender and anything and anything what should I do mmm create constructors let's try this one consider with this in which I would paste this and then I will use the mad G the the magic stuff meaning LJ multiple quarters and then this and then the Rideau it's a bit stupid to call your own letters you do that only few narcissist or something so just this this and this and then you guess what these are redundant LJ there you go so this means to push the conversion inside the constructor of the DTO which is fine it's okay for the DTO to depend on the entity god forbid not the other way around details can depend on the holy stuff on the entities but not the other way around of course now if you do this this method it's kind of silly I mean what was the purpose of this matters anymore right what the heck so let's inline it right in line the method here in which place it will be yellow again so we don't think I'll tend to drift yeah it means that your reference is based basically basically the constructor is a function that takes the user and gives you back the instance the new instance there we go the method referencing of a constructor which is which is pretty cool now it's in a whole bunch of different ways of doing these method references so I will do the best thing that you should be doing more often which is control zero control zero comes from undo it takes a lot of strength of psychological strength to admit that you've screwed it up that you've did a bad bit code is worse that at the beginning so I will undo undo it should undo ten times per day it's healthy it's healthy just an undo undo undo undo undo and this is the method and lets me and once more okay good good and there you go good and then this conversion is piles up this fade at some point it will annoy me that's why that's when I will move it out to another class right let's name it a user very wisely user mapper huh extra user wrapper and I will move this out good and then of course if you make this a public class intelligible complain don't you want to make it to a separate file please and you will enter and move it so it's easy to extract them just work in a single file I find it more more fast just in one file move things together when you when you're done out know just public art enter out know the tool know the tool use a map and then I will need somehow here a private final a private final user and then the question is where do I get the function from well this should be public for sure but then it is interesting where is the function is actually you could write the the slow motion stuff giving any user you could go to mapper and to DTU but the IntelliJ will tell you it don't know Java that much do you I don't enter again alt enter here III did something wrong I should pass the user first make it from pile and do not enter enter there you go nice not first is control shift space will work here to do anyway mapper to do so this is another way of referencing the method and it is method of another let's pretend to be a service right you can it can inject it very nicely like this and then there you go you can reference the method of an existing spring binge superpower for I have dozens of such example in a production code it is very convenient to go fish you inject an instance and then you go fish several methods from that instance those methods could call down some repository stuff ok so you can play with the functions and further however since we got here case we got here it's okay it's okay to actually I was to tell you that later let's this is the first example after this is for example you feel like ah you're strong so the next thing you do us saturate you come to work and you want to prove that you know Java 8 you have to prove your to your colleague that you know Java 8 but they will have your head they will have your head on the place this is your head so the problem here is or there's that string it begins easy but then filter creation date is after local date now - okay okay this is actually actually a sense this is last year oh what the heck is this but just moving it up you're done and then alt enter you will save your day oh yeah otherwise I am concatenating all the order lines together in one single big bucket you see this this is a stream of order line but no more order for you and then I will glue byproducts famine hint and here comes the fun part and reset stream actually the fun part is even is these three lines if you ever see these three lines take a walk take a shower slap your head and what this does is like imagine you have this this this and you put this bucket and in the bucket you make a hole and pick pick pick down what are you doing why don't you collect everything because you you are collecting everything actually right so this is a missing opportunity to explain what the heck is the result of this method so click here variable control Alvey selects the somatic block which ends there and says say what are these actually these are so I'm collecting grouping by product of the order and you know when you place an order you can be ordered three tables in one chair right is that these are actually two lines to order lines for and then basically you will group by the product and sum the number of times you've ordered each product so this is actually product order counts or cons video and then from that method whenever you get the point in which King collection to a collection do it do it and explain what you have here there are famous cases in which you can't do that if you are streaming from the database of over 1 billion rows you can't just collect everything of course you will be forced to stream stream stream stream that's the reality but whenever you can do that do it entry set stream ok filter e are get very more than ten business requirement okay map and then you take the key out of it and then you feel it or not to be deleted oh wait a second I can write it even even even more elegant how by the way who knows Lombok oh this is equivalent of let me just quickly quickly show what this does really this technically does Gator a gator for the time wait wait wait wait yet not yet no very private long it is written and then set and then set and then also of course you need you you can't live without food equals you just can't leave and of course it was drink so now the question is very simple what do you prefer you prefer this or just two lines not of course if you are going to function programming into in more depth in Java you will eventually want to use data structures and basically data gives it for free but again Lombok is a two-way sort is it sometimes it's the tool too powerful for many teams if you don't know design if you don't know P if you don't know what you are trying to achieve and if you start to take data on your entities this is game over you lose so pay attention with Lombok and don't go for all the experimental features don't use valve please don't use valve if you if you are that man angry on java go to code name of karla even better but yes okay so basically this is deleted is hidden somewhere there below but look what I can do yes yes I can do something interesting I can you find a public Gulen yes what yes it is not deleted actor yes but it returns returns excellent excellent but this has to be a method okay so then if I do this what can I can use it instead and then if you press enter is a mess but if you press this one saves lives my friend Tom yes and then it's yellow art enter there you go nicely done referencing the product a predicate built inside the entity's super you start with Java it to have this little predicate spread over your entity model but then comes the horror part because you realize something here my friends what the heck is this what the heck is this is a method and repository what the heck happens what the heck happens here reference this lambda is executed how many times for each and every oh this is the famous and plus one queries in which you run a an expensive operation in the loop it's not visible because it's not a four but it's it's there okay and this one is this will make the SQL query that you see identical in your log right so then what could you do well I know I know I know let me extract this one this two predicates done the rest of the problem now I'm keeping a function this is a bad name for for the with the second I've overridden the predicate I'm keeping in a predicate a function okay this is something weird in Java is just a function is never cold unless I use it here and it will be cold for it didn't do anything good actually so what should I do instead is to run the query once before I loop and I make it a variable variable hidden Product ID is very well it extracted it there but no words I can move lines away and this is grayed out so there you go so hidden product IDs now happens just once pay attention here of issuing queries in the loop because somehow by some meet some methods you go to the database pay attention very very it's not that visible anymore it sometimes it is harder to detect so that's a bit better but then I can do even more I can extract all these to a method which is something I do ten times ten to twenty times per day extract methods and I will name this get yep get product counts if I do this with a method I would explain even better because you see this method has more than five lines I'll get it off there we go if I win which case this one is no longer means that I will inline it which is quite good now we can tweak it more one idea would be to take this one now this is this is a tricky point there are opinionated ideas one will be to take this and this is actually the product if you look careful which were ordered more than 10 times okay let's make it a mess variable okay frequent products now some people when they feel variable of type store type stream they have an like because yeah it's weird especially if you pass around that streamed many methods you don't know who the heck if it's consumed or not it's it's a mess so that's why you need to ask do you really want to stream like or or could you collect two lists I have to do this first and then here but okay in which place this is not used alt-enter maker makes the product this is frequent product okay now I know that I am streaming again from the collection but I am not afraid to do that I got I gained is a variable which explains in a collection of human brains works better with collections it's a collection of product a stream what the heck is that is the stream of more okay so it's easier to read and now you can even make a method out of it yet frequent products frequent products products there you go and in line is good so you know how a juggle I extract things are you make variables I mean methods I make I'd give names stuff I make new predicates on the on the on the entities that I work with things that I juggle with now some people even go further and say okay let's extract this what does this mean really variable product not hidden I would feel I have awkward feelings about this honestly I'm not entirely convinced it's a good idea but it could explain a bit better code a bit this is your code I just I'm showing stuff okay good make sense make sense good next one oh-ho-ho do you know I'm Tony the Tony Hoare the so called surcharge on Tony Richard Sir Charles and he's a sir what did he do good in this world let's read I call it my billion dollar mistake it was the invention of the new reference in 1965 he invented noon ok ok so let's wash away the problem that he introduced let's say so we have this class this card account service which has a method public strings get applicable not yet discount string which takes not sure about this a customer is a customer a customer customer control shift enter we'll just just call up just to be cheap again I was there I was there I don't care well control shift enter finishes the statement industries and then I will say something like return discount percentage equals plus get discount of of customers dot get member card now this method I will create f2 alt enter enter and I will do card and then I have this business rules they have to implement if and only if where the test should have test if card dot a fidelity parts more than five no more than 50 then what return three present of 5% reduction and this is another string is then int and then else if if card gets identity points are not more than 50 but more than ten return 3% otherwise return moon this is your code to write the another developer gross this not your code noon okay and then let's make a main and in the main I would say something like new discount service dot well I want to get the discount string for a new member card which has a new novel and new canoe customer free which has a new member member card card with exactly 60 or not receive six is two is busy 20 25 30 points okay and this this thing I want to print another another beautiful stuff dot s out and then he thought they're nice extract this is a variable name it'd be very wise me good and then run it ctrl shift f10 300 prints yes yes three percent bingo you have to believe me let me just it is good now and then this other one more death case which is giving it exactly five point five point five points what should I see what a new lady the debtor this is a noon and you this is your explain to the business my dear business this is a new you don't know that noon noon is what we do it work it's so then what's the problem you rush to find the problem and want to key one key technique here select the constant string in the console like this control see as directly takes you to the point enter and it gets it to where the disease coming from so well what's wrong oh this god this was returned noon oh my god what should I do let's make this variable named B and then if you know if if the equals null now if not if it's not equal then return this this dispute here okay else return the beloved Penta string X and the business feels nothing it's better than moon but nothing good yes but then you walk the open space not a beautiful place and you know here in some corner some people here but optional whenever you see moon he was optional and you start wondering what why do I see what was best for noon there and then you figure wait I didn't knew that this method would give me a null and I will concatenating the noodle blindly to the string this is where the nude came from at which moment you realized wait a second wait a second I know I know I know I know I should return here what an optional as a rule of thumb whenever you are returning nothing to your color don't be rude and give it a noodle because it he might not expect that but instead return an optional of something and off now this is pretty straightforward what what I was completely puzzled when I when I when I show this to some to some teams where that they left null here now this is completely outrageous this you should initialization you should because in two pieces and the Sharks I mean any folks good and now we do you have a problem but that's good they have a problem it's not an integer it's not an integer and what do you do you make it is variable to be an optional and you replace this to be if if it's a perfect perfect excellent it's I will have a problem D is no longer an integer is an optional of integer and then what do you do well I know yep but but this time even intelligent you will figure out you are a fool because it will ask you this should I replace this with an functional style yes please I want to do excellent I couldn't have said it better thank you and then D it's not I'm gonna do I will inline it enter here and there you know this is the function it does very nicely what happens really you know this one gives you a box not not not any integer a box which makes you wonder what is inside if it's a cat or not you know Schrodinger's cat box and you start thinking that's good because in then you can map in which means you use the map somehow corresponds to you putting your hands inside the inside the box with a with a with a with a spray and spraying in red everything if there was the cat it's now it's a red yet if there's nothing it's nothing now okay so basically this is this is map or an optional transforms the contents if there is the content otherwise then it returns nothing good but then comes the ultimate test the ultimate test which is discount customers with no member card run and you know Chris de Burgh Chris de Burgh had one song lady in red this is it and your breath your breath you know you have lost for words that's the feeling and we an ingrate shame you run desperately to fix the problem you click here and you see that this line throws your pointer of course it has responded this is me so then what do you do you do what you know best you put a nice if card equals knew your mother I returned no not me oops my fav level for you and good three person I accident I start but then but then you think a bit and you again go to that corner which would where were some geeks are working it they are saying that that you should every time you've seen moon and there is new and then comes this first to you why am I doing this this is this is call my friend this one defensive the fans if programming equals terror but the problem is that this thing that you get that you got might come noon so then what can you do there is the same that the best defense is the offense so what do you do you think you start thinking where does this came from here aha aha and now my friends something incredible you will touch the holy things about this is the holy domain we need so here you were coming you will say because you know you know this is interesting we will talk tomorrow when moon has a meaning it should be wrapped safely in an option even when it comes from an entity so what what I mean is make here optional whenever something might be might come not new to you always and you know you once set them the the field to optional hibernate or whatever it won't be very happy but they will say off new Nobles and you bridge the gap between the new world vo your API will return this to your pure colors which we like which might extinguish the moon just incredible but then this doesn't compile what do you do you use the cool technique for anything year which is Earth driven development by painter art enter Victor what happened now I change first parameter of method to take an optional oh my god what the heck is this even IntelliJ complains that you should not use optional as a parameter why because these shouts out loud that your function does two things one for the empty case one for the non empty case right I know that I can make it work I know yeah I can fix it in the end I can fix it I mean I can do it but but this is not the way to go right this is not the way to go it will eventually work but it's wrong it's completely wrong so then what could you do no sir if it suggests anything no it doesn't it's too hard for the heat for IntelliJ so then what what can be done now the point is whenever you have an optional you should always consider starting with the optional Oh starting with it so or suddenly get membercard is no longer giving me a member car but an optional of member car so let's start with that one dot if there is a member coverman map based on the card then apply the get discount on that card oh my god a play apply on that and no longer optional just plain member card and don't take optional instead map map to them from the exterior and then map further and this is what you should return now of course IntelliJ also and there you go this is what you should but this is perfectly perfect it's done the problem is that the integer now is an optional of integer not an integer anymore and then you notice the beauty if in any night in the winter that comes you have a long night next to a fireplace with a chatting up in your lap read about monads I won't talk you about morals today I will just silently say here flatmap see that it works and move on I won't do this with you today it works the problem is sadness tips one of the extra wrapping right just flat map from strings you know that the flood map from optionals gives the way one of the wrapping that's not a big deal really but it has to know about this function now technically I'll go further with you today do you know that model that you have class 8 which has a prior private BB which then has a getter for it and then you have a class D that obviously has a class C in the side with a getter for C then C and what you want to do is actually just from an a to a see you note that the classic scenario you have an A and you have a dot yet B gets it the so called train wreck one of these there might be not this or this who knows which one so this is a place where if you switch to optionals and you make all of them return optional leather studies why not I think I can fix this let me check how we can do it I'll J here an optional of C or B I don't limp I don't care exactly what wrap it option is good you wrap it up the first time I do this honestly and then this get beat thing we'll get you an optional that you can then flat map using however vehicle it be I think it works be that gets it and what you get back in the end let's instantiate it here is actually it actually an optional fee and in case you wanted to to string.c you would write to string then I will write here map and do two strings from and this gives me Mack an open and an optional of string that but I don't know and that I want actually to or else nothing which gives me the string now this is a type safe way of navigating a mod not a fit no safe way of navigating a model but it would whatever but the point is you can get rid of the moon from this chain it's you've all seen such things breaking somewhere in between you don't know where with fruit and we did that I called this adoption of optional inside your Gators of your entity I I call it game one this is Game one against noon because the the last place in which news will come to you is your own entity model right have you ever heard of non moon not on this one not null and it's not this not new no board isn't this one is this on spring not new and not new API super cool means print up a GPA ensure that you never get a noodle from the spring defy repositories super cool no frameworks killed the null but you still have news in your own and it model so folks this is the ultimate I'll call it the ultimate level of adoption of Java if you do this the new leads out of your business right but there is also here this the beauty for example one more example super interesting so let's say I want to build this order this class order exporter exporter which I will need the order ripoff for sure the private final or the rapport rapport and then let's use magic to inject the dependency and then you need to have public void export order CSV there go with a string file name and in which you do what you need open a file of course or the fine name and then if you know how to write your code you know that you should never write variables because alt enter enter okay good and then I should try and open a new file writer file the writer of that file whatever file and then this is a writer I should make a file I'm not sure if it works here obviously okay and then this is a try with resources f2 f2 alt enter I have a colleague which annoys me very much he doesn't use the mouse it doesn't use the mouse at all it puts it like this in front of me it does control eat a lot I'm so angry this throws so throw yourself but not not that let me let me throw it out out good and now in this writer you should raah you should write but yeah a line is right the first is let's say username and full-name in which which is a CSV remember right and then we what we do on the order RepA we will say fine back through which gives us a stream interesting one because there are 1 million of them right and we love picked up view is using spring data GPA brings up a GPA then what we are persisting re persisting you guys don't know you can find all stuff yeah Chloe's don't know it's purely stuff the rest of you are doing swing applications what what are persisting beta - what - a file no really - what what kind of database for again who is a relational relational relational relational relation we love relations on but not on hibernate right Oh hardcore stuff gdb see here in case you are using this it is give stream and then you will map converting each order to a bee-utiful all that get IB behaves as the username and then plus and then this and then oh not yet creation they have full name creation date anyway good and they go and then you have a stream of things that you have each of them to refer to for each each of them you have to write to the writer so given a string I will say a writer dot write string okay I know what you're thinking I'm missing an enter right I'm missing an enter so this will trash my whole demon because you don't enter is critical okay and this will write a sting but I'm done oops it doesn't compile what alt enter right try catching and throwing again because because web has for each takes a consumer which doesn't throw anything doesn't throw anything but my right throws the point is you this method uses checked exception you should suffer if you are using checked exception it's you to suffer but this case you don't will control the API right so that's why you have another option actually unchecked from Jules Verne now not sure but that consumer which ad which technically does exactly what you just did but this is a bit weird to write but this is adding the form which makes for dot and if we import this one God have mercy of your soul what the heck is this this is my friend is something you should never show to your children it's a function that takes the function it returns the function what the heck it's a higher-order function of the order of the ugliest kinds you should ever should avoid writing such functions yourself trust me I've been debugging such functions for years and it's a mess if you go to the ball mode you're doomed because returning functions if you don't step in - step out it will go like this - the coat pom-pom it's it's a mess so taking function as a parameter is okay but returning functions yet another game that's another in Java honestly is not prepared for such a game in my opinion so still this is the library thanks to you this pretty well known okay why not but then comes read the change request of course every story finishes with the change right that's the the reality and the change request says that I want to export the the users in the same way in the same way and same way in your head means copy paste so export user see just for fun just to see what what we change right I will need to import some some things like user repository report user okay and then of course I won't stream from I will stream from is a repository find all and then I need to open the stream because this doesn't return me thank you and then I will map and this is no longer oh no longer what a big mistake you you get ID if I keep writing down tell me to raise the screen if I keep forgetting and you get the username and then you got you what what export user okay and you get good and this is pretty lame and lastly I think I did something wrong here this is ideal but are you changed this line and this line if the rest is the same hmm actually these are more interesting because you see in the beginning the you also don't just draw dry misery now it's bad practice right what you do it you are a man you can handle it through no first thing you do any cash an exception the first thing you do the first thing you do you load it you never know you never know another try don't trust your colleagues to log it correctly no better driven development loading and you print you got message oh and then you throw again but you throw it in a nicer way in a random exceptional e but I love that enough what you did after you copy pasted code is that you changed this block the exterior block remains the identical this is also the same always the same only the same so then what what can you do there are several six of possibilities to implement it I won't show you the functional one right at the moment you realize that this is what you need to actually do you will keep this close to you safe to you in a safe place and of course delete the copy pasted code right this is a key technique duplicate the code a bit see what changes take what changed take it out and then see how you fit it in then these changes directly for for the Java is solution what can you do idea this is variable from one useless to another what can you do what can you do and please don't stick don't tell me please please don't tell me about about buland's if user export please don't tell me about bonus you can extract let the map refresh the point is this is also different you see so I would actually yeah that's one thing but you'd also need the header so why not be more generous and extract what it all that I do with the resource oh that I do with the resource with resource resource so I will take this out and first step is to extract this in a method I will limit and then this F takes a writer and returns mind if I would like to get here f as a parameter what should I write what what function takes the writer and returns nothing back of humor when similar like a sink we throw at it and it just disappears consumer over writer into which is actually the so-called content writer nice this content writer has the same signature so technically speaking you will just invoke it with the writer nice but then but then comes the this is this is when you have an epiphany like wait a second just export should I end the class here and create another one which is something like or the class or the export content writer me interesting interesting to host already specific stuff which is specific to exporting the orders whoa whoa whoa this becomes interesting it smells like design I don't think so design can we do design with functional programming don't we don't just do filter for my future purpose we can do design design the fence design me let's play with it new order exporter export matrix not other exposure is wrong it is the CSV export or five or whatever and then on the end this is quarterly happy but not border CSV as you read it you refactor it you don't think it's one second to effort but CSV and then you give it the words that this is a the first one with a what a order orders CSV and then you pass in what new space control but this is triple this is just what should you give here that the interesting part but you need somehow to reference this function right well let's start to do this so I will need first this is an instance method to reference an instance method in a normal way we should do this this is the the the order content let's say and then from the order content you can for that I miss something I miss something private oh let's make it public and I won't forgot yes and it doesn't compile just a second here I will need here an order repo but why do I take another deposit I'm pretending to you spring button on teaching spring let me just switch to that just give up this is pretending and I will just put here Auto art okay I will pretend Louie wrote one know this pretend and then here it doesn't compile why can you see why without looking at the error which is a good exercise order start to anticipate the error exception and then I will do something wrong very wrong very wrong I will delete the throws from here I know anything you can you can do this and wrap it with it with it with it with a try-catch I know I know I know but it's so ugly so then what do you do and this is the second level Lombok I call it it adds a try catch it catches everything and which throws it at runtime but avoid you doing try catches a tree throw it does it for you automatically right during the bicycle that you have on the disc there will be the try catch good a second I have a problem with my mine and then far out aw good idea in creation did nice this high mountain height we throw the exception of run time to play nice with the function and programming you were on the river the heck happened with my screen it's getting dark dark matter and then here this actually what doesn't it work incompatible types writer is not convertible to file writer I didn't pay the tension I should have a writer here which is actually a better design let me let me take you there slowly first of all this is the main it's clear for everyone right if I would like to export the other type of of of of data I will probably create another class class which is user export content writer all right I'm just curious if I still have the photo of Mario yes I'll show it to everyone really brilliant if you don't know how what name to put to a variable put such a name you will be ashamed to put push it on get but I will you read it there we just found it and collect ideas okay Wow I make Hockley Pro housing you will be ashamed to push on it and now users per container and then you say this and you will actually have to inject this we'll pretend this spring here and then we will we will have this other F ready as well as you see it you say write content don't think just the leches cup is too easy to copy/paste right and then remove the content put this in place and there you go you're almost done expect the exception and you it's yeah I don't know who put this yet okay so then e1 to export now this time the user new user expert Content writer this is User Content and then author User Content and then User Content dot right column that is right there don't think rename when you see a typo don't hesitate don't ever edit it it takes one second right good and this is a big mistake this is actually users now let's come back to the design part what the heck happened now tell me one thing how would you test this okay you know that tells that you don't have tests that test you just how would you test this thing honestly how would you test this thing maybe just other pretend pretend is pretend public you are smart guys you can figure out the missing pieces public void test writer how would you test is really probably you need to instantiate the class blah blah blah but then what would you do you will call the method with what with some file ok and what would you do it here you will probably write a dummy content and then assert that on the list appeared this dummy content makes us and of course it needed a an end consumer two times control space and you have added two cons humor unchecked with her and shake be consumer double long with the first news of course it was the first time of course it is I'm really curious did they really did you implement the artificial intelligence to suggest this what I heard anyway consumer and then good now this is a this is an evil kind of need to go to the disk back how where is the real thing that you need to test here nicely isolated from anything that has to do with resources why how would you test this one let me put me let me pretty play with you test and then actually I have this but this this test X and then how would you test is you will have to instantiate new order export content or the export content writer and this is this is system under test but terrible name set and then and then that X but right content now watch how would you test this one you would pass in what a string right ah nicely done what is the screenwriter it's a kind of writer which for a string will enter and after the code the production code you have string writers dot to string and you get the actual value back that you compare to something that you expect the point is there are no files in the play there are knots nothing with file system nothing it's all in memory so this kind of free factoring this is called the lung pattern why because technically you are loaned a resource which you don't have the trouble of opening and closing and blah blah blah blah blah you just are loaned a writer you just blended it right to the writer and that's it you'd never have to concern yourself with anything else right which is super interesting it's more testable right now what's happening we tried technically to apply the clean code rules the old clean code rules in Java eight names we the clink of Maineiacs love names but basically since I got here yeah I still have ten minutes something I know it's the end and people normally introduce at the beginning but nevermind relate I forgot you forgive me and the question really what do you do when something you know if you very much but you cannot avoid doing it but don't tell them what do you do do what do humans do do they they leave it for tomorrow who knows if tomorrow it will still be needed and tomorrow they become manager or leave or what do they do them if you're a boss with with a hard problem you are delegate but it's not very productive what you should do instead instead do it more often to bring the pain for or bring the Prince for already the philosophy behind the extreme programming extreme programming as I mean who knows about extreme programming extreme extreme extreme but now for those of you who don't know if the programming doesn't mean you will go paragliding while coding no extreme programming means to be a professional and the four things which are now is us most and in life are if you are on your own branch for two months three months four months six months you're ready smell the merch after the merge comes the code review the so called don't wait for the inevitable okay asked for help ask for the senior to help you but prepare his ground meaning drawn the window explain the problems visually if at first I mean do a little presentation for this I know the scenes are super busy do a little presentation to slides with your problem okay pair programming asked for help know when to ask for help and step on your pride continuously factoring because the otherwise you know where it leads us it leads us part production code her continuously factory should be proud of every pull requests if submit proud of the code each right what was the last time you were proud of something that you did at work you should feel this at least weekly daily possible right be proud of your work and the first and most terrible thing wrong is code that you have don't have automated tests on the matter what else if you'd if you're afraid of touch the code it is the end what do they say don't wait for the tests print you need tests print that is not such a thing don't wait don't do post-it don't write separate posted the implementation refactoring testing no because business will come into will take the testing post-it for off your flip chart so no do them do them together even first try to the right test first or at least when you push to push them together right now probably that angel lost its original meaning initially angel doesn't mean you will run fast there are actually people back then who in the day up cabinet today are somehow they regret the name they chose in a way because when they we say angel to the business it sees this it's his lunch it can throw features of you of course with the six deadlines and the deadlines the fact is they're not in dictionary' means the line between around the prison if you pass over they you get shot without warning the to get shot the first the first meaning of the deadline in the dictionary the second one has to do with time so subtle craftsmanship is the movement who tries to resuscitate those four practices DVD / programming in contrast restructuring and technically speaking I swear I will never push code without refactoring I swear I will write test I swear I will never harm another human being hypocrite oh so yeah our Victor okay the second Java champion in Romania I'm an internal coach at IBM moving from team to team and I am stealing I became because I hit my own legacy there I love my own legacy it's my own garbage so beautiful so a programming every day every every day I never wrote code alone in production for the past 11 months or even one year don't Citicorp exactly refactoring every time I was so happy factor you are duty huge your hands in code whenever I see something wrong she step 6 I found this community in Bucharest where are now 1100 people already it's only Romanian unfortunately it's all spoken in Romanian lives webinar that I do for all the people who want to grow those skills back home I have a playlist on YouTube but the point is that I have a website they did at the point of the slide I have a playlist on YouTube on which I if you pay attention to those selected talks you can find out most of my training curricula because that's what I already I'm a trainer I've been training for quite a long it's a lot of speaking a lot a lot of too much speaking the point is I teach Highbury Springs every design practice architecture don't even design yeah-ha clinical unit testing t DB DD and I will play a bit with it let's get the first a performance car I teach on O'Reilly with the big guys that and but the point of this slide is that I have I posed as a maniac not such good content like murder here I'm reporting what he did with the MOOC what finger so yeah what I'm posting stuff now that's not free but this just for me because it's only remaining yet so names I always say that clink of many EXO I needed to explain my family I am a clean-cut man I have a diploma lambda has mean anonymous functions and we the clinical many I have a problem with anonymous we love names they talk to us that's why I should never have fear if you never find this token in your code base never ever ever ever ever whenever you see that extract lambdas into methods that you reference with four dots like we did remember to detail simple as that good in the same class in the item class is not deleted remember is or even maybe in another class or a static method there are you can play with it just reference them it four dots clinical says five lines shorter methods and then I know that some of you can implement this thing or your entire use case with one single instruction you do return you remember the example query string don't do this we have children don't do this don't do this instead explain them with variables methods explain them explain those those long expressions Klingons said no little parameter because if you take a null parameter the first thing you need to do is to check for moon and there is this principle some of you may have fun s therapy think responsibility principle the s installing principles which says the function should do one thing but if you do check for moon and the other thing yeah think so then on the parameter this basis Java is me is no optional parameters right what should do instead is is map from the optional and apply of function selectively so drink instead avoid returning moon prefer to throw exception is possible because we didn't have the other tool because if you return a null to someone who doesn't expect an old lady that's what you get so what in Java each decision is simple do you certain option arise like that crazy good don't be assertive of Orcs monads or flatmap don't be afraid of them passing to Brock we just did that we passed the function to another function like that well Zach but that was the point and this might represent the funeral of template method as we've seen today we have template method isn't a class with an abstract method that you provide by suit class and so the sub classing you can pass in the missing function imagine that yes there is a function and this leads us to the loan pattern which is a flavor of the passing block in which you work with a resolve that is managed for you with that like we did we are also a string writer that we did not but with auto writer that we need that create actually now this is super cool because it's the coppers logic from infrastructure do you remember do you do division template query and I come the raw mapper okay and the thing is this was doable before this is doable for the decade okay but we generate it's better nice and maybe extract this block to a method and don't do this here it shouldn't be here who did this so make him enter the reference method now there is another thing so there are two flavors in your design there can be two two possibilities one is that you want in a common bit of blood in a comet chunk of logic to put one thing or another but you have the big chunk the other way of going that is that you have some method that you want to run in the transaction you see you start from what you have inside and you wrap around it it's a circle though it's a so-called of explicit AOP you wrap it longleaf carcass not that much of that but aspects passed out to pass carcass is different than love how many of you know about carcass meet with yeah yeah you measure and this is how you can measure how it takes for you to save a page right he's testing a number in its of a void checked exception you should suffer if you were work with non runtime or I should suffer which is good but in case someone else throws the checked exception to you you can use jewel I think that was the framework to unchecked about consumer we saw the thing or sneaky other things we did we didn't do that thank you I don't know I'm not sure how is the local habit here but I already did two to talk to little folks but there is pizza here so of course now will you eat pizza but I will ask you again afterwards in half an hour let's say about twenty nine suffer if you want to do some more code if you want to live code something maybe some TDD examples just slow motion now if there will be ten of you remaining we will end it but if there is interest of that we can stay longer I'm not sure if you have sunrise I'm sure how is the habit here not entirely sure so no pizza and I will ask you again in 30 minutes what should you do okay [Applause]
Info
Channel: JUG Milano
Views: 1,537
Rating: undefined out of 5
Keywords: JVM, Java, JUG, JUG Milano, Functional, Functional Programming, FP, Stream, Java 8, Voxxed, Devoxx
Id: fmzIO-RK1B8
Channel Id: undefined
Length: 76min 1sec (4561 seconds)
Published: Fri Dec 27 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.