Developer Skill Sprint: Refactoring Legacy Code to Design Patterns - Daniele Teti

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi I am Daniel 880 I am an ambassador MVP and CEO beat em professional a software company which provides consultancy trainings and custom development based in it today we will talk about the refactoring and the same patterns the concept which will skill sprint is about can be applicable in own platform languages but the sample will be Delphia specific during this skill sprint will try to answer to the following questions what's refactoring what's refactoring to pattern why I should care about it and then after some introduction we'll see a like them let's start with a brief introduction about the refactoring what's refraction refactoring is a controller technique for improving the design of an existing code base which simplifies back lower the code maintenance cost and to have an idea return on investment and a lower TCO to the cost of ownership and the refactoring last but not least keeps developers happy and what about the same patent the definition of the same pattern is quite popular and say that the design pattern explains a general designer that dresses are occurring the same problem in object-oriented system design patter improved developers discussion because you have a shared vocabulary about what you are working on and speed up the learning process for new team members which is quite important for all sides member all sides team and allows to learn more from the others experience from the other people that are working on a similar problem that you're working on now and simplify deliver the book which defines their factoring as we know today is this one it's gone it's from Martin fuller which introduced the refactoring process the book is around 70 refactoring it stuck above 70 refactoring described in details and several development environments this is quite important Delf include automate many of their factoring described in this book and we will see a couple of it refactoring has become a full-fledged part of the software development lexicon so it's quite important to master the concept exposure in that book and just as a natural evolution of the first book this is the second important book refactoring to pattern it is book by Joshua KDM ski and it's a marriage of the refactoring wit pattern and suggest for example that using patterns to improve an existing design is better than using butter early in the new design and this is true whatever code is years old or minutes old now this is the introduction so let's see some real code with some live demo we'll see some general refactoring supported by Delphi editor and some does fit specific refactoring this is a simple dollfie application would show one of the most let's say popular code pattern in the Delphi developers mine historically this is a form with a button a progress bar on this box I have here a main data model with a connection to learn to base database or what the busy like and a query which there's a select stars from so I start from cast on the data model is almost empty because have holiday components drop it on the design on the designer and then all the code is on the main form or at least they are truthful under the button so I I'm doing some fake customer processing I start doing the clearing the list bots where my cursor will be added and then reset the progress bar position property open the query and then look through all the data set doing the actual process and after close the query it's a quite popular it's a quite popular but say code pattern in the Deaf world what's hard the problem this is quite I could smell because we are accessing we are accessing with a higher level of intimacy with the components on other form or other data model so we can help problem to maintain to maintain this disk code because it's not correctly separated i have code which update user interface here mix it with code which though the actual with just the actual work so how we can improve this code using refactoring let's start with a live demo I have here the enterprise which have this fantastic the new refactor with the refactoring engine let's start with the refactor let's see how this application works its run and then here as you can simple understand click in the button I see my customer filling the leaf box doing some obscure processing ok let's improve this this code to make it simple to maintain and easily tested let's extract the dis code which actually access data from the image citation data the user interface related data select this go to refactor and select extract method this extract method is one of the most important refactoring pattern it's simply extract a selected number of row inspecting the code understanding what are the variable used so you can using this refactor you can separate your code so also long methods can be cutted down and short of a more manageable size method you can also access it using shift ctrl M extract method or so the choosing the correct name it is a really important part of a factoring phase in this case we can call this method destructive method process customers process customer ok and then the Delfy factor engine extracted the process customer method and call it where before the code where were directly written so this code has been extracted by this position in a new method ok now our code our application works does the same job as before but is quite better now but we can do many many things to make this application better for example we can extract from this method we can separate the user interface related code from the data access code as you can see these three lines have to are related to the user interface this free line can be refactoring a lot to separate user related user interface of related code from the other data access code but the inline variable can make this quite complicated so as a first as a first step we can use the introduce variable refactor I can select the part that which I have to I want to substitute with a verbal right click refactor introduce variable refactoring here I can call this the verbal l progress progress that's it in 64 and then we use this variable instead of directly assign value also here when I want to hard there when I add the customer name in the list box I can use the same the factor introduced verbal al Kessler and now I have two new verbal our customer and al progress which I can put directly to the start of their or the wildly now the code can be easily separated I can select this and reapply the extract method refactoring Ahmet will do with us it's quite simple updateui you can use also more specific methods but for now sk updateui is this code running in the same way yeah we can we can try it now great bottom yeah quite a same way but now it's more separated and which is a good things as you can see this code now is a bit more a bit more manageable is a bit better but there is also there is still a big problem of the big problem of this code we are accessing darkly the main model they made a data model here in the user interface code which is quite bad but now I have a more cleaner method here in the process customers there is no directly reference to the user interface code so I can use another factor which is called move method but Dafa doesn't support the move method for instance for instance metal if I try to move the metered you can only move study method to another class or class to another namespace because this is quite complicated to do it but we can do easily by hand we can copy this code go to the main method pass here change the name of the class and then control shift see automatically limited is created here I have to move this private method to public can't save it and now this process customer can be removed from the main yeah from the main phone if I try to compile this there are obviously error because process customer doesn't have update UI method so we can add another parameter you to the process caster which is the connection between the data model and the user interface code what we can use I think that our anonymous method can be enough so we can call this parameter on progress and declare it st brauch string unsigned integer that - yeah and add the same also here in the Declaration and now this update UI become a call to the a on progress using the same values now the process customer should works fine but I don't have but one its progress now is L customer l progress customer projects because of string you okay now this process customers doesn't have the general Emil's method to actually update the user interface but it's quite simple to introduce it procedure we can also copied to the declaration but this is quite simple our customer string progress win32 yeah you have to call the process customer on the main DM okay it works but we have to actually call the update UI code to update UI the customer here is a progress and the customer it compiles run it was as before but what we done what we did we simplified a lot the code in the user interface which could be also under an action list for example and we strongly separated the user interface code from the code which actually does the work we can obviously remove the reference to the minted model here because simply wrong okay so now in our the model disease there is the the processing the actual processing code we are called back to update the user interface but we don't know the user interface and this is a unimportant an important object that we reach it while the user interface code doesn't access directly to the data and this is another important thing that we which this is a quite simple process which show applicable applicable to the to many many old or legacy or also new development code in Delfy when you have the Data Manager in the user interface yet rethink about your process and move the death data that code in the data model or in our service classes or something that is not the user interface and here we have used a couple of refactoring pattern introduced by Martin for in the fairness book for a brief recap we talked about extract and method we talked about introduced and we talk about which is the this is refactor are supported directly by Delphine so introduce verbal instruct method and then we also use the move move method refactoring but we we did the work by hand okay we saw some basic code refactoring but obviously this is not on the solar power Factory in the working folder book there are a lot of refactoring patterns which allows to improve the existing and occur the design of existing code in this slide you can see some of them I strongly suggest to read this book if you want to write better code or if you need to maintain your legacy code there are factoring techniques introduced in the fuller book are really useful also to in to use the same pattern in the legacy or a new code the book of refactoring to patterns teach how to do it this is absolutely another suggested reading as we told a reading the skills printer factoring a star so when you write your second line of code don't trust your first attempt to structure your code to your design but use the refactoring to improve it every time you touch it first some learning resources and she of duffy enterprise or better be sure to understand all the potentiality of their factory engine inside the tool here you can see the link to the document to documentation if you have and of enterprise be sure to understand the concept so that you can do it by hand and then this is the details of the to Bookman mentioned in this the skills print and if you want to follow training you can also check a bit and professional trainings or ask information about it ok guys thank you for your attention so is the extraction refactoring smart enough to relocate local variables yes it is can reallocate the level variables moving them to instructive method as needed and he can understand also if in extract admitted you are actually modifying the local variables and that local variables will be passed by reference so it's quite smart to extract me that so Jeff saying that it seems like the code became more spaghetti like what what exactly is the purpose of the refactoring why is it we went through we broke a single method inaudible methods moved it around well the first thing you can you can see this code quite a strange because you are used to have all your code in one place and so on but don't you get once you get used to do the correct way to separate responsibilities which is one of the most difficult things in computer science and brilliant software in general is absolutely bad things you can do because it's very very difficult to understand maybe 50 lines hundred lines metered hundred lines code meters compared to the to a normal to normal 3 10 20 line at best metered so if you can separate the responsibilities in the long term it must also in the short term you have a big big gain internal productivity in term on time to the bugging and so on obviously in a demo simple like this one which are maybe 10 lines of code the big the big Gaines is not so here but you have to extract the ideas and apply that to real real code real Ward the problem then you will see really a big a big gain in your productivity and also because you can now separating the responsibility separating the dead access code from the user interface the related code you can start to do actual testing you can unit test it you can do automatic testing for the not you I related code so it's absolutely and must you cannot do in different way if you want to be really productive and so on you know that's a really good point that it makes it easier to create unit tests what is the C++ the equivalent of anonymous methods in C++ 11 you have the fantastic lambda expressions which are really more or less 101 related to anonymous method C++ 11 had some some details more specifically compare columns method but for our needs are absolutely replaceable with anonymous methods and while if you still don't use C++ 11 and I strongly suggest you use C++ 11 also because new in Delfy in a super fast builder 10 c odd oh there is support for suppose was 11 auto for windows 32-bit target which is really really good I start to to like C++ another times and you could you can also use on C++ 0x you can use some mechanism to extract interface from the anonymous method and elf aside but in space level is very very simple yeah the lambdas are really really great feature there's a lot of cool stuff in C++ often that's that's true yeah yeah would it be possible to directly past the updateui instead of declaring an honest method which invokes updateui yes but you have to pass a metered pointer and you still don't get to much gain from the anonymous method stuff I strongly suggest to make it confidence with the anonymous method because they really really simplify your development and makes your code more modern and you don't have to pass sender and so on you can just write your code where you are you don't have to declare it something passed a method yes you can you can do it but try give a try to the anonymous method because it really makes your code better this is my personal experience and I think it is really shared experience yeah not as methods it's kind of a little different because we're not used to writing code that way but it's one of those things that I found once you wrap your brain around it and start using it it really lets you do some cool things that you just never could do before and it just makes a lot more powerful and like you said it keeps your code where you want it instead of having people put it someplace else so I think it makes it easier to maintain you know such as well yeah when I went happened they have to work on program we would old the Delfy version and I don't have generics I don't have anonymous method I don't have extended our TPI I feel quite compressive because once you start to use animals metal and generics that you are really confident with them your your mind will change to use that yeah it's kind of like object-oriented programming I remember because I've started programming back at aura pastel and I brought objects or in programming came out like I don't see the point of that I mean I can just do all this stuff in procedural programming you don't need these objects that's just extra fluff and now that I understand the concepts by an object in programming and how it helps you to structure and have larger programs it's like oh yeah I wouldn't want to go back to Percy so it's one of those paradigm shifts that takes a while yeah yeah yeah absolutely so I also pointed out that you couldn't declare a method pointer in a separate unit and set it to point to the procedure and use that one in the method to work with the procedure yes you can although I think anonymous methods is a better way let's see question here about okay so asking about passing like data directly to something like the the T chart from schema passing able to be plotted how through that who should be responsible for that data yes you can yes you have to identify in your code what is your model what is the data which should not be directly in the user interface but you on see you once you have identified your model you can use that instance that reference to pass all over your your application layer to make it to make it the user interface be updated then if that model acts like let's say a subject in an observing design pattern you can just move the model you can change the model and then the user interface is updated but if your model is a data transfer object or just like a value object on something else you can modify your model and then use some code to update the user interface just like we did here in in the demo use that model to update your user interface let's say you could have a reference to their data set which does something and you have to pass death data set connected to the user interface in some way using the source the be grid summer grades and so on to the different layer which actually acts on that data set you can disable control path data set and all the layers do something on this data set and then when all the layers return it you have to just enable control you don't have to update your user interface because the component already did it for you but if the object is not so evoluted is not so connected interconnected that you have to do it manually but you can use the same approach also with other components it's always bothered that's a good point yeah make sense so David's saying I could see there factoring bit and that was great but where does refactoring patterns come in how is how is it we've refactored ok ok ok we had two separate two concept refactoring patterns and refactoring to design patterns you can use the refactoring patterns to support they were factoring to patterns let's say the first book the book from marking polar actually talks about refactoring patterns so extract method introduce verbal move emitter the move class and so on using that basic refactoring bubble included also in belfry also in other tools which are really standard ok really standard it makes sense to use it also if you could in Delft in C++ in other languages whatever using that basically factoring you can apply all this or factoring to create architecture based on design pattern but you have to know the design pattern and then here the second book can be useful to understand how to use the basic refactoring to a specific design pattern and and then this is the difference one is the let's say the little brick where you can build your building to make the the all the architecture based on design patterns the difference you used the refactorings in order to go from the way the code was implemented to now the code follows the patterns that were defined in the the patters book yeah refactoring to the level supported by Delphi is on the roadmap for C++ can you tell when tell us what might actually appear on the time scale I believe that is on the roadmap for this year if I recall correctly Roger so it should be something you look forward to this year yeah the design patterns are there were those things that I think for me at least took a little while to understand and why that was in the the part you point out where it's about improving the vocabulary I think is really a good point because basically are you read through this and like I've done this before and that's the point is it's what it's doing is it's going through an identifying useful design useful patterns things that we've done before other people have done before and how to redo those so by once we've identified these patterns then we can reimplemented assess the Wolters asking do all these new procedure calls make the code slower so that's a really interesting question Walter so there's two things to consider first of all the compiler does automatic inlining so inlining means if the procedure is a very small procedure call movies done a lot the compiler will automatically take that procedure call and unwrap it if you will into the place that's being called from so it can automatically inline small procedures you can mark procedures as inline if you want to give the compiler a hint that you think this should be inlined but the compiler can make that decision automatically as well so first that's first of all second of all the making perceived your call is a couple additional instructions most of the time we're waiting on the user or the database disk access etc we're not waiting on the CPU so if you're in a situation where you have a loop you're doing a lot of processing then that is when you want to consider the optimization of pulling out additional procedure calls most likely the impact is going to be in conceived imperceivable to any users if adding additional calls in here so so the answer is yes it makes the code slower but the reality is it's making the code more maintainable and being more maintainable makes it easier to fix issues and stuff so it's kind of a you don't want to get ahead of yourself in saying oh I got to put everything in one procedure so it's faster no that's not the case you're not you're probably not have any bottleneck there that you're hitting Thomas just added to send my experience often refactoring results and faster code over time because the code becomes better maintainable and it's more organized unless yeah unless you're optimizing something that is because running you know keeping the CPU pegged for a period of time then it's not it you're not you don't optimize for slowness optimized for maintainability and then if you discover it slow use a profile or find out where it's slow why it's slow and then address speed issues there is another comment here does adding new methods in variables use more memory than before so similar to the idea of having more calls being slower again it may use marginally more memory but it's probably not going to be an impact it's the CPU or the system is able to page memory in and out as needed first of all second of all so let's say you have some code and you have an integer using up at the top that's called age okay and then later on you have another place that you want to use another integer in this in here and so you would declare a new integer called count now if you never use both age and count if you use age for a while and then stop using it and start using count behind the scenes the compilers say you know what I don't need to keep age and memory anymore so I'll remove it from memory and count can then use that memory so even though your code is easier to understand because you have two different variables there with two names that specifically define what the variables are doing it's not actually using any more memory okay so the compiler is doing a lot of optimizations for your code to make it behave better the OS is doing optimizations for keeping things in memory that need to be a memory maybe a memory so again don't sacrifice maintainability and readability of your code for some worry about things being taking up more memory now maintain your code make refactor make an optimistic optimized and then if you discover using a profiler that you are using more memory look at where you're using memory chances are it's not in adding an extra integer to your routine to make it more readable more maintainable it's probably somewhere else where you're keeping a data set a copy of a dataset nourishment like that so yeah so Neal just pointed out premature optimization is real all evil I don't know that it's the root of all evil but it's certainly it's one of those things you need to understand the scope and impact of things so you know realize you know what I probably don't need to have the entire database in memory that's the purpose of the database is like the database handle that so that's a good idea but worrying about having additional variable declarations or additional procedure calls to make your code more attainable that premature optimization you don't need to do okay so a link that probably says premature authorization is the root of all evil so take a look at that so Richards asking there are factoring books use Pascal or C++ for demo code I think they use C or C++ possible probably they don't think they use Pascal but they do actually have like UML diagrams and stuff like that I've read here and read all three of those or at least consulted all three of those and they were very informative very helpful if you go to the page here actually this down here says important refactoring patterns this links to some pages that have the UML diagrams and go in just the start of kind of what's covered in there so see this is and this is C code here so that's not there's no mo diagram there for that one so see here this has UML diagram so it's in the book the code examples may be in C C++ you're going to be able to read it I would have suspect and it's just explained in UML explained in text the benefits and such this is are there so you should still be able to take advantage of it I think one of Nick Hodges coding in Delphi books also cover some of these techniques as well so definitely take a look at that nice interpreting programming yes this is a great I thought this is really well put together the modeling tools Enterprise are equally suitable for refactoring yes that's very true actually Thomas the in Enterprise has the Enterprise Edition which we have that great sale going on right now for has some modeling tools in there and design pattern just like that which really actually quite powerful if you go in there you can say hey I need to refactor this and you do this round way more powerful than the stuff that was shown here we should probably do a video on that because it's really cool stuff can we use refactoring to improve code performance so we can't touch it unless earlier when you refactor code it makes it obvious where it makes it easier to find the places you can improve performance it makes it easier to understand the code so that is how you can improve it so it doesn't refactoring doesn't typically improve code performance directly so technically refactoring is modifying code to make it easier to maintain without affecting its behavior so it's not you're not refactoring to improve performance but you refactor it you're like you know what I see here I am doing this is really you can discover where you're doing things that are really not well optimized where you're doing things that are maybe you're copying something multiple times or you don't really need to you only need to have at once for example you could have maybe some code peppered throughout the form that really should be or you could have the same code over and over and over again where it's allocating the same thing maybe it's going out reading the same table from the database in the memory multiple times that's not efficient so if you discover that in your refactoring you're like you know what I need to make an object over here that maintains that okay maybe it goes out and checks to make sure the table hasn't been updated or something like that but once you you can make those discoveries through refactoring that make it easier to improve the optimization so for example if you went through and implemented the refactorings that were shown here where you separated the data access from the user interface in the future if you're like you know what hey we got some new you know originally used bTW but now we're gonna switch to fire back if all that code is in one routine one unit because it's all your data module that's a whole lot easier to refactor and move from B to e to fire back then if it's peppered throughout all your user interface code and so you can make those changes resulting in big performance improvements without having to go through every source file in your code which makes it way easier to maintain the same is true for fixing bugs that's true it's way easier to fix bugs with once you've done this and see this is really the key behind refactoring and design patterns is maintainability if you think about it your code spends way more time and maintenance than it does in development so it really is important to consider that to make your code more maintainable so George's saying that the code that the end was a little more difficult to read than the original he missed the point the code that he was here that he showed was really really simple code when you have production code and you have your UI code and your data access code mixed in together that's gonna be huge probably have huge routines by separating this out it makes it easier understand easier to maintain especially if you have like a team of people you can have one person that maybe understands this one unit all the data access really really well and somebody else understands you I really really well or you can have make changes to just mid access or just the UI without having to modify every file in the application so the more you can decouple your code which is way showing here the easier it is to maintain in the long run this is like I said a very simple code example chances are if you look at your code you have and think about what parts of this are going to access what parts of this are updating user interface and how would I separate those apart want you to go through those stages of making that you'll see that it breaks things apart into smaller pieces making it easier maintain you know if you can't see an entire routine on the screen nice to be my rule of thumb if I have a routine that has more lines than I can see on my screen doesn't mean by a bigger monitor although bigger monitors are nice it means it's probably doing too much in there and I can't look at that and understand what's going on if you could look at it understand what's going on it makes easier to debug easier maintain inline directive after current method the guarantee and lighting so in light using the online method does not guarantee inlining it is a hint to the compiler the compiler will ultimately make the decision whether can in line something or not at least that's my understanding of the way the compiler works and the reason is is because you may put in line on something that can't be in line for one reason or other so if you do have in line you will get warnings for example saying hey this can't be in line because you're not using this unit that so let's say for example you're in unit a and you have a routine in unit B and unit B uses unit C and you try and in line a routine from unit B and that routine uses you routine from unit C if you a doesn't use unit C then it can't inline the routine in unit B and you'll get a warning that you need to fix that if you want to have them things in line so it can only ever be a hint otherwise you could generate broken code would doing this on fire monkey Sloane app down and add to memory use we already addressed that not notice big number of procedures shouldn't be an issue otherwise we'd never write software with any procedural and make a few big ones correct more procedures and routines is easier will the demo code both before I could be available especially the callback part I will get it we'll get that to the download page hello actually just updated the page with a link to a code rage session that Jeff LaFave did previously on maintainable code Iker some of the same sort of information kind of the idea it some of more ideas so if you do want more information about this check that code rate session out and it's about an hour long video with QA and everything on there so I see there's that YouTube video of separating logic and UI which connects to a question I think that Lucas has there about what about when you're creating an entity would it be a good idea to put it in a separate module in a separate unit in case they put it in a day to module then instantiate them if you need them yeah you could certainly do that really this is about loosely coupling it and then when you look at your application and realize you know what I have to separate you know data models modules really you could you know I'm sometimes I'm using these objects and language needs these objects I don't ever need these or rarely ever and you use both then yeah sure make them except for a data module initial instantiate the one individual data modules you need yet really this is about you know looking at loosely coupling your code making sure that each routine each class is very focused on what it does so it's not doing too much because the more it does the harder it is to maintain I never was saying really liked what I already saying a webinar that does more about refactorings that we support that would be great and that's a definitely a good idea maybe also some little shorter little how-to videos on each of the different rare factories right I'd be good in relating them to back to Martin Fowler and other people who a lot of time on this so I'll add refactorings and the IDE to my expanding list of short how-to videos that we'd like to build and we're also looking at what other webinars we're gonna do for the rest of the year so stay tuned for all that thanks for the suggestion okay well thank you so much for your time and thanks you for this great skill sprint alright we'll talk to everyone later see you all next time bye bye bye
Info
Channel: Embarcadero Technologies
Views: 8,258
Rating: undefined out of 5
Keywords: Embarcadero, Delphi, C++Builder, RAD Studio, Developer Skill Sprints, How To, Refactoring, Design Patterns, Refactoring Legacy Code, Application Development, How to Refactor Legacy Code, Object Pascal, C++
Id: St-8aY5GREc
Channel Id: undefined
Length: 48min 23sec (2903 seconds)
Published: Mon Mar 28 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.