MELJUN CORTES Java Lecture Refactoring


Published on

MELJUN CORTES Java Lecture Refactoring

Published in: Technology, Design
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Different types of Refactoring
  • It is a discipline way to clean up code that minimizes the chances of introducing bugs. When you refactor you are improving the design of the code after it has been written
    Over time the code will be modified, and the integrity of the system, its structure according to that design, gradually fades.
    With refactoring you can take a bad design, chaos even, and rework it into well-design code. Each step is simple, even simplistic. The cumulative effect of these small changes can radically
    improve the design
  • Refactoring was conceived in Smalltalk circles.
    Two of the leading proponents of refactoring are Ward Cunningham and Kent Beck. They used it as a central part of their development process in the early days and have adapted their development to take advantage of it.
    Ralph Johnson lead a group at the University of Illinois at Urbana-Champaign that is notable for its practical contributions to object technology. Ralph has long been a champion of refactoring, and several of his students have worked on the topic.
    Bill Opdyke developed the first detailed written work on refactoring his doctoral thesis.
    John Brant and Don Roberts have gone beyond writing words into writing a tool, the Refactoring Browser, for refactoring Smalltalk programs.
  • When you use refactoring to develop software, you divide your time between two distinct activities: adding function and refactoring. When you add function, you shouldn’t be changing existing code; you are just adding new capabilities.
    When you refactor, you make a point of not adding function; you only restructure the code.
    Swap hats and refactor for a while. Once the code is better structured, you swap hats and add the new function.
  • Refactoring is rather like tidying up the code. Loss of the structure of code has a cumulative effect. The harder it is to see the design in the code, the harder it is to preserve it, and the more rapidly it decays.
    There another user of the source code. Someone will try to read your code in a few months time to make some change. Programmer easily forget that extra user of the code, yet that user is actually the most important.
    Clarifying the structure of the program helps other programmer to understand the code and spot bugs.
    Improving design, improving readability, reducing bugs. All these improve quality. A good design is essential for rapid software development. The whole point of having a good design is to allow rapid development.
    Designs don’t hold up. Decay over time. Back in line or improve using insights
    Read more than write. Process of refactoring increases understanding.
    Challenges assumptions, simpler code leaved fewer places for bugs to hide.
    * Bit rot is a colloquial computing term used to facetiously describe the spontaneous degradation of a software program over time. The term implies that software can literally wear out or rust like a physical tool. Bit rot is also used to describe the discredited idea that a computer's memory may occasionally be altered by cosmic rays.
  • The most common time to refactor is when programmer add new feature to some software. Primary reason to refactor is to help programmer to understand some code needed to be modified. Once refactored, adding the feature ca go much quickly and smoothly.
    In fixing bugs much of the use of refactoring comes from making code more understandable. This active process of working with the code helps in finding a bug.
    Refactoring also helps the code review have more concrete results. Not only are there suggestions, but also many suggestions are implemented there and then.
  • Design in advance helped avoid costly rework. The analogy is design is an engineering drawing and code is the construction work. But software is very different from physical machines. It is much more malleable, and it is all about thinking.
    With refactoring as an alternative to upfront design, this scenario you don’t do any design at all. You just code the first approach that comes into your head, get it working, and then refactor it into shape.
    Refactoring can lead to simpler design makes the design process easier and less stressful. Once you have a broad sense of things that refactor easily, you don’t even think of the flexible solutions. You have the confidence to refactor if the time comes.
  • A common concern with refactoring is the effect it has on the performance of a program. To make the software easier to understand, you often make changes that will cause the program to run more slowly.
    The secret to fast software is to write tunable software first and then to tune it for sufficient speed
    With well refactored code you can add more function quickly. This gives more time to focus on performance (with the help of a profiler)
    Profiler lead to smaller parts of the code, which are easier to tune. Because the code is clearer, you have a better understanding of your options and of what kind of tuning will work.
  • A Short well named methods increases the chances that other methods can use a method when the method is finely grained. It allows the higher-level methods to read more like a series of comments. Overriding also is easier when the methods are finely grained.
  • You use short methods named to show their intention, because these method lead to clearer and easier to read code. But sometimes you do come across a method in which the body is as clearer as the name. Or you refactor the body of the code into something that is just as clear as the name. When this happen, you should then get rid of the method. Indirection can be helpful, but needless indirection is irritating.
    Another time to use Inline Method is when you have a group of method that seem badly factored. You can inline them all into one big method and then reextract the methods.
  • The only time Inline Temp is used on its own is when you find a temp that is assigned the value of a method call. Often this temp isn’t doing any harm and you can safely leave it there. If the temp is getting in the way of other refactorings, such as Extract Method, its time to inline it.
  • The problem with temps is that they are temporary and local. Because they can be seen only in the context of the method in which they are used, temps tend to encourage longer methods, because that’s the only way you can reach the temp. By replacing the temp with a query method, any method in the class can get at the information. That helps a lot in coming up with cleaner code for the class.
  • Expression can become very complex and hard to read, In such situations temporary variables can be helpful to break down the expression into something more manageable.
    Introducing Explaining Variable is particularly valuable with conditional logic which it is useful to take each clause of a condition and explain what the condition means with a well-named temp.
    Another case is a long algorithm, in which each step in the computation can be explained with a temp.
    Warning: don use this as much you might prefer using Extract Method.
  • Moving method is the bread and butter of refactoring. Move methods when classes have too much behavior or when classes are collaborating too much and are too highly coupled. By moving method around, You can make the classes simpler and they end up being a more crisp implementation of a set or responsibilities.
  • Moving state and behavior between classes is the very essence of refactoring. As the system develops, you find the need for new classes and the need to shuffle responsibilities around. Consider moving a field is you see more methods on another class using the field that the class itself.
  • Class should be a crisp abstraction, handle few clear responsibilities, or some similar guideline. You add responsibility to a class feeling that it’s not worth a separate class, but as that responsibility grows and breed, the class becomes too complicated. Such class is one with many methods and quite a lot of data. A class that is too big to understand easily.
  • Inline Class is the reverse of Extract Class. Use Inline Class if a class is no longer pulling its weight and shouldn’t be around anymore
  • If subclasses are developed independently, or combined through refactoring, you often find that they duplicate features. In particular, a certain fields can be duplicates. Such fields sometimes have similar names but not always. The only way to determine what is going on is to look at the fields and see how they are used by other methods. If they are being used in similar way, you can generalize them.
  • Eliminating duplicate behavior is important. Although two duplicate methods work fine as they are, they are nothing more than a breeding ground for bugs in the future. Whenever there is duplication, you face the risk that an alternation to one will not be made to the other. Usually it is difficult to find the duplicates. The easiest case of using Pull Up Method occurs when the methods have the same body, implying there’s been a copy and paste.
  • With constructor, the common behavior is often the construction.
  • The opposite of Pull Up Method. Use it when you need to move behavior from superclass to a specific subclass, usually because it make sense only there.
  • Opposite of Pull Up Field. Use it when you don’t need a field in the superclass but only in a subclass.
  • Methods should be named in a way that communicates their intention. A good way to do this is to think what the comment for the method would be and turn that comment into the name of the method.
  • Add Parameter is a very common refactoring, one that you almost certainly have already done. The motivation is simple. You have to change a method, and the change requires information that wasn’t passed in before, so you add a parameter.
  • Programmers often add parameters but are reluctant to remove them. After all, a spurious parameter doesn’t cause any problems, and you might need it again later. By not removing the parameter you are making further work for everyone who uses the method. That’s not a good trade-off, especially because removing parameters is an easy refactoring.
  • MELJUN CORTES Java Lecture Refactoring

    1. 1. Refactorin g MELJUN CORTES Improving the Design of Existing Code MELJUN CORTES
    2. 2. Topic Coverage  Background of refactoring  What is Refactoring?  Where it came from  Principles in Refactoring The Two Hats Metaphor  Why and When  Refactoring and Design  Refactoring and Performance 
    3. 3. Topic Coverage (cont.)  Bad Smells  What is code smell?  Types of code smells  Types of Refactoring  Types of refactoring.
    4. 4. Backg round of Refactoring What is Refactoring? Where it came from
    5. 5. What is Refactoring? Refactoring is the process of changing a software system Refactoring is the process of changing a software system in such a way that ititdoes not alter the external behavior of in such a way that does not alter the external behavior of the code yet improves its internal structure. the code yet improves its internal structure.  Disciplined way to code  Over time code will be modified  Changing code in small steps  Verify no change in external behavior by – Testing – Formal code analysis by tool
    6. 6. Where Refactoring Came From?  Ward Cunningham and Kent Beck Smalltalk style  Ralph Johnson at University of Illinois at Urbana-Champaign  Bill Opdyke’s Thesis g/  John Brant and Don Roberts: The Refactoring Browser
    7. 7. Principles in Refactoring The Two Hats Metaphor Why and When Refactoring and Design Refactoring and Performance
    8. 8. The Two Hats Metaphor Adding Function • Add new capabilities to the system • Adds new tests • Get the test working Refactoring • Does not add any new features • Does not add tests (but may change some) • Restructure the code to remove redundancy Swap frequently between the hats, but only wear one at a time
    9. 9. Why Refactor?  To improve the software design  Combat’s “bit rot”  Makes the program easier to change  To make the software easier to understand   Write for people, not the compiler Understand unfamiliar code  To help find bugs  Refactor while debugging to clarify the code  Refactoring helps you program faster.
    10. 10. When to Refactor?  To add new functionality  Refactor existing code until you understand it  Refactor the design to make it easy to add  To find bugs  Refactor to understand the code  For code reviews  Immediate effect of code review  Allows for higher level suggestions Don’t set aside time for refactoring, include it in your normal activities
    11. 11. Refactoring and Design  Special role as a complement to design.  Refactoring can be an alternative to upfront design  Refactoring can lead to simpler design without sacrificing flexibility
    12. 12. Refactoring and Performance The best way to optimize performance is to first write a well factored program, then optimize it.  Refactoring make software go more slowly  Refactoring makes the software more amenable to performance tuning  Well refactored program gives you time to spend on performance tuning  Well refactored program you have finer granularity for you performance analysis
    13. 13. Types of Refactoring
    14. 14. Extract Method You have a code fragment that can be grouped together Turn the fragment into a method whose name explains the Purpose of the method. void printOwing(double amount){ printBanner(); //printDetails System.out.println(“name:”+ _name); System.out.println(“amount:”+ amount); } void printOwing(double amount){ printBanner(); printDetails(amount); } void printDetails(double amount){ System.out.println(“name:”+ _name); System.out.println(“amount:”+ amount); }
    15. 15. Inline Method A method’s body is just as clear as its name Put the method’s body in the body of its callers and remove the method int getRating(){ return (moreThanFIveLateDeliveries()) ? 2 : 1; } boolean moreThanFIveLateDeliveries(){ return _numberOfLateDeliveries > 5; } int getRating(){ return (_numberOfLateDeliveries > 5) ? 2 : 1; }
    16. 16. Inline Temp You have a temp that assigned to once with a simple expression, and the temp is getting in the way of other refactorings. Replace all references to that temp with the expression double basePrice – anOrder.basePrice(); return (basePrice > 1000) return (anOrder.basePrice() > 1000)
    17. 17. Replace Temp with Query You are using a temporary variable to hold the result of an expression Extract the expression into a method. Replace all references to the temp with the expression. The new method can then be used in other methods. double basePrice = _quantity * _itemPrice; if ( basePrice > 1000) return basePrice * 0.95; else return basePrice * 0.98; if (basePrice() > 1000) return basePrice() * 0.95; else return basePrice() * 0.98; ... double basePrice(){ return _quantity * _itemPrice; }
    18. 18. Introduce Explaining Variable You have a complicated expression Put the result of the expression, or parts of the expression, in a temporary variable with a name that explains the purpose. if ( (platform.toUpperCase().indexOf(“MAC”) > -1) && (browser.toUpperCase().indexOf(“IE”) > -1 && wasInitialized() && resize > 0 ) { // do something ... } final boolean isMacOs final boolean isIEBrowser final boolean wasResized = platform.toUpperCase().indexOf(“MAC”) > -1; = platform.toUpperCase().indexOf(“IE”) > -1; = resize > 0; if (isMacOs && isIEBrowser && wasInitialized() && wasResized) { //do something }
    19. 19. Move Method A method is, or will be, using or used by more features of another class that the class on which it is defined Create a new method with a similar body in the class it uses most. Either turn the old method into a simple delegation, or remove it altogether. Class 1 Class 1 aMethod() Class 2 Class 2 aMethod()
    20. 20. Move Field A field is, or will be, used by another class more than the class on which it is defined. Create a new field in the target class, and change all its users. Class 1 Class 1 aField Class 2 Class 2 aField
    21. 21. Extract Class You have one class doing work that should be done by two. Create a new class and move the relevant fields and methods From the old class into the new class Person Person name officeAreaCode officeNumber name getTelephoneNumber() getTelephoneNumber() Telephone Number areaCode number officeTelephone 1 getTelephoneNumber()
    22. 22. Inline Class A class isn’t doing very much Move all its features into another class and delete it. Person name getTelephoneNumber() Telephone Number Person areaCode number officeTelephone 1 name officeAreaCode officeNumber getTelephoneNumber() getTelephoneNumber()
    23. 23. Pull Up Field Two subclasses have the same field Move the field to the superclass. Employee Employee name Salesman name Engineer name Salesman Engineer
    24. 24. Pull Up Method You have methods with identical results on subclass Move them to the superclass Employee Employee getName() Salesman getName() Engineer getName() Salesman Engineer
    25. 25. Pull Up Constructor Body You have constructor on subclasses with mostly Identical bodies. Create a superclass constructor; call this from the subclass methods class Manager extends Employee ... public Manager (String name, String id, int grade) { _name = name; _id = id; _grade = grade; } public Manager (String name, String id, int grade) { super(name, id); _grade = grade; }
    26. 26. Push Down Method Behavior on a superclass is relevant only for some of its subclasses Move it to those subclasses Employee Employee getQuota() Salesman Engineer Salesman getQuota() Engineer
    27. 27. Push Down Field Two subclasses have the same field Move the field to the superclass. Employee Employee quota Salesman Engineer Salesman quota Engineer
    28. 28. Rename Method The name of a method does not reveal its purpose. Change the name of the method Customer getinvcdtlmt() Customer getInvoiceCreditLimit()
    29. 29. Add Parameter A method needs more information from its caller. Add a parameter for an object that can pass on this information. Customer getContact() Customer getContact(:Date)
    30. 30. Remove Parameter A parameter is no longer used by the method body. Remove it Customer getContact(:Date) Customer getContact()