Beruflich Dokumente
Kultur Dokumente
Submitted By
ANIL ARORA
(10/05)
What it Refactoring?
Refactoring is a disciplined process of
changing a software system in such a
way that it does not alter the external
behavior of the code while at the same
time improves its internal structure.
This is sometimes called “Improving the
design after it has been written”
INCREMENTAL DESIGN!
(Very) Simple Example
Consolidate Duplicate Conditional Fragments
if (isSpecialDeal()) if (isSpecialDeal())
{
{
total = price * 0.95;
send() total = price * 0.95;
} }
else else
{ {
total = price * 0.98;
total = price * 0.98;
send()
} }
send();
Principles
The purpose of refactoring is to make software
easier to understand and modify
Contrast this with performance optimization
Again functionality is not changed, only internal
structure; however performance optimizations
often involve making code harder to understand
(but faster!)
Why should you refactor?
Refactoring improves the design of software
without refactoring, a design will “decay” as people make
changes to a software system
Refactoring makes software easier to understand
because structure is improved, duplicated code is eliminated,
etc.
Refactoring helps you find bugs
Refactoring promotes a deep understanding of the code at hand,
and this understanding aids the programmer in finding bugs and
anticipating potential bugs
Refactoring helps you program faster
because a good design enables progress
Why should refactoring be done?
public Account() {
}
}
//Move Field Example AccountType Class Before
package refactoringlecture.moveFieldBefore;
public AccountType() {
}
}
//Move Field Example Account Class After
package refactoringlecture.moveFieldAfter;
public class Account {
public Account() {
}
}
//Move Field AccountType After
package refactoringlecture.moveFieldAfter;
double getInterestRate(){
return _interestRate;
}
public AccountType() {
}
}
Extract Class
1. Decide how to split the responsibilities.
2. Create a new class to express the split-off
responsibilities
3. Make a link from the old to the new class
4. Use Move Field on fields to be moved
5. Compile and Test
6. Use Move Method on Method to be moved
7. Compile and Test
8. Review and reduce the interface of each class
9. Decide whether to expose the new class.
// Extract Class Example Person Class Before public String getOfficeAreaCode(){
package refactoringlecture.extractClassBefore; return _officeAreaCode;
public class Person {
}
private String _name;
public void setOfficeAreaCode(String arg){
private String _officeAreaCode;
_officeAreaCode=arg;
private String _officeNumber;
}
TelephoneNumber getOfficeTelephone(){
public class Person {
return _officeTelephone;
}
private String _name;
private TelephoneNumber public Person() {
_officeTelephone }
= new TelephoneNumber(); }