Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

26
Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics

Transcript of Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

Page 1: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

Refactoring (continued)

Lecture 7CIS 6101 Software Processes and Metrics

Page 2: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

5.1 The Refactoring Cycle

• Basic pattern for refactoring with a working program:– Choose the worse smell– Select a refactoring that will address the smell– Apply the refactoring.

• Select refactorings to improve code each trip through the cycle.

• Program’s behavior is not changed.• Thus, program remains in a working state.

– So cycle improves the code but retains behavior.

Page 3: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

5.2 The Refactoring Cycle

• Trickiest part of process: Identify the smell!

• When you start refactoring, best to start with the easy stuff (for example, – breaking up large routines or – renaming things for clarity).

• This lets you see and fix the remaining problems more easily.

Page 4: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

6.1 Simple Design Always!

• One approach is to seek the simplest design.

• Kent Beck (XP) for simple design – four rules

• If your code violates these rules (in priority order – coming) then you have a problem to address.

Page 5: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

6.2 Simple Design• 1. Run all tests• 2. No duplicated logic.

• Be aware of hidden duplication like parallel class hierarchies.• 3. State every intention important to programmers

– Internal comments (me)• 4. Code fewest possible classes and methods.

– As long as choices conversant with good design! (me)

• A shorthand name for these rules is OAOO, which stands for once and only once.

• Maintenance can complicate this with a code and fix and re-release to the field! Not always time….

Page 6: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

6.3 Simple Design

• Code has to state something once so that it can – pass its tests and – communicate the programmer’s understanding and intent.

• Should say things only once: no duplication!

• Difficult to clean up code not kept clean; • Few teams can afford to turn the lights out for months on a

quest for perfection.– You will not be given the time from employer!

• Can learn to make our code better during development• Add a little energy each time we’re working in an area.

Page 7: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

7. Extreme Programming and Test Driven Development

• XP is an agile software development method characterized by a particular planning focus, and programming through tests and refactoring.

• Programming in XP is built around – simple design, – test-first programming, and – refactoring.

• Write a test, see it fail, write code, see test pass.

• XP proponents claim programs developed this way will have – fewer errors and – be in less need of big refactoring that typical code requires.

• While refactoring can be done with a simple text editor, supportive environments make it easier. XP is a supportive environment.

Page 8: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

7.1 Extreme Programming and Test Driven Development

• Tests: Best for refactoring to have a test suite run before and after refactoring to ensure you change design of the code and not its effects.

• “If you want to refactor, the essential precondition is having solid tests.” (Fowler)

• Can do this in my classes. Present test file with answers. Work to accommodate!

Page 9: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

7.2 Extreme Programming and Test Driven Development with JUnit

• JUnit is a testing framework (www.junit.org).Test).• Classes extend the TestCase class and contain methods

whose names start with the word, test.• This framework provides a number of assert methods to let

you verify the code’s behavior.

• Comes with a test runner to run a suite of tests.• Some simple but powerful IDEs have built in refactoring

support. • Java has had such support for a number of years; • C# is gaining more support.

Page 10: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

8. Inside a Refactoring

• Example: • Named Refactoring: Encapsulate Field.• Goal: make clients of an object use methods

to access a field rather than have client methods access a field directly.

• Goes back to ‘public’ and ‘private’ visibility

Page 11: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

8.1 Consider the Codepublic String name;….public String getName() {return name;}public void setName (String newName) {name = newName};

Martin Fowler’s catalog tells us to (steps in order)1. create getters and setts for the field. Why??2. locate all references; replace access with calls to the

getters and setters

3. compile and test after changing each reference4. declare the field as private5. compile and test.

Note the careful, simple steps!!!Note the change, compile, and test to verify behavior!

Page 12: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

8.2 Consider the Code

• Refactoring is a step by step process.– Refactoring works in tiny, deliberate steps.

• Most refactorings tend to take from a minute to an hour to apply;

• Average is probably five to ten minutes.

Page 13: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

8.3 Refactoring Example Step 1Step 1: Create all getter and setter methods.So we have:public class Person {

public String name;}// end class Person

The test client looks like this:

Person personperson.name = “Bob Smith”; // note: directly accessing an attribute – because it is public.AssertEquals (“Bob Smith”, person.name);

Step 1: Create getters and setter methods:public class Person {

public String name:public String getName() {returns name); // added getterpublic void setName(String newName) {name = newName) // added setter

} // end class.

Note that the client is unchanged; no code is calling these new methods yet!!

Page 14: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

8.4 Refactoring Example: Step 2• Step 2: Find all clients, replace all references with calls.

– Do this one at a time. And test each one!!!

• One way to find those references is to temporarily make the field private; • if you do this, your program will not immediately work. So you are doing this to

identify clients of this class.• Be certain to change visibility back to public scope before changing the clients so

you don’t break any clients at this point.

• Note: some compilers will tell you if things are not going right When you change the visibility keyword and recompile, you get a warning that some client is still using the method.

• Because warning is at compile time vice run time, you’re protected while you refactor.

• Assignment: person.name = “Bob Smith”;• Becomes• Person.setName (“Bob Smith”);

Page 15: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

8.5 Refactoring Example: Step 3

• Step 3: Compile and Test• Refactorings have the goal of having an improved system,

– But many have bases, safe points, or interruption points. – Most refactorings have built-in bases.

• There are instances where we can stop along the way and at least have partially improved code

• Nevertheless, it is progress toward a better approach.

Page 16: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

8.6 Refactoring Example: Step 4

• Step 4: Once all clients are changed, make the field private.

public class Person{

private String name;public String getName() {return name;}public void setName(String newName) {name = newName;}

} // end class

Page 17: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

8.7 Refactoring Example: Step 5

• Step 5 – Compile and test one last time.

• Again, we’re safe and the field is completely encapsulated.

Page 18: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

Introduction to Smells• The smells we will talk about are easy to detect.

• They are common.

• Can think of these smells as being caught by a software metric.

• Each metric tends to catch different aspects of why code isn’t as good as it can be.

• Others try to measure the connections between methods or objects;

46 18

Page 19: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

Introduction to Smells

• Most metrics seem to correlate with length. So let’s worry about size first

• Metric noticeable as a – Large Class or – Long Method.

• But if a metric is easy to compute, we will use an indicator that some section of code needs a closer look.

46 19

Page 20: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

Introduction to Smells

• Metrics are indicators, not absolutes.

• Easy to get into the trap of only looking at numbers without addressing the total complexity.

• So don’t refactor just for a better number

• Make sure it really improves your code.46 20

Page 21: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

Code Smell (Google)• A code smell is a hint that something has gone

wrong somewhere in your code. – Use the smell to track down the problem.

• Kent Beck coined the phrase in the "Once And

Only Once," where he advocated simplicity.

• Bad Smells in Code was an essay by Kent Beck and Martin Fowler, published as Chapter 3 of Refactoring Improving The Design Of Existing Code.

46 21

Page 22: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

Code Smell (Google)

• Note that a CodeSmell is a hint that something might be wrong, not a certainty.

• A perfectly good idiom may be considered a Code Smell because it's often misused, or because there's a simpler alternative that works in most cases.

• Calling something a Code Smell is not an attack; it's simply a sign that a closer look is warranted.

46 22

Page 23: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

Code Smell (Google)• There are two major approaches to programming:

– Pragmatic: CodeSmells should be considered on a case by case basis– Purist: all CodeSmells should be avoided, no exceptions

• CodeSmell is a hint of possible bad practice to a pragmatist, but a sure sign of bad practice to a purist.

• KentBeck or MartinFowler wanted to emphasize the pragmatic view of CodeSmells by the connotation of the word smell. – If something smells, it definitely needs to be checked out,

but it may not actually need fixing or might have to just be tolerated.

• See also CodeStench, but note that all CodeSmells are CodeStenches to purists!46 23

Page 24: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

Code Smell (Google)• We have seen this definition: A code smell

is a surface indication that usually corresponds to a deeper problem in the system.

• Quick definition contains a couple of subtle points.

• Firstly a smell is by definition something that's quick to spot - or sniffable.

• A long method is a good example of this - just looking at the code.– There is often a smell if the method is more than a

dozen lines of java.– But some long methods may be just fine.46 24

Page 25: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

Code Smell (Google)• The best smells are easy to spot and most of time

lead you to really interesting problems.

• Data classes (classes with all data and no behavior) are good examples of this. – You look at them and ask yourself what behavior should

be in this class. – Then you start refactoring to move behaviors in.

• Often simple questions and initial refactorings can

be the vital step in turning anemic objects into something that really has class.

• 46 25

Page 26: Refactoring (continued) Lecture 7 CIS 6101 Software Processes and Metrics.

Code Smell (Google)One nice things about smells:

Easy for inexperienced people to spot them, even if they don't know enough to evaluate if there's a real problem or to correct them.

Sometimes a lead developer will pick a "smell of the week" and ask people to look for the smell and bring it up with the senior members of the team.

Doing it one smell at a time is a good way of

gradually teaching people on the team to be better programmers.46 26