REFACTORINGXP Injectionhttp://xpinjection.com
Do You Know Your Code?
Developer Golden RuleAny fool can write code that a computer can understand
Good Developer Golden RuleAny fool can write code that a computer can understandGood programmers write code that humans can understand
Why Fix What is Not Broken?
If the Code is Hard to UnderstandHard to maintainHard to improveHard to work with evolutionary designMore expensive
What is Refactoring?A series of small steps, each of which changes the program’s internal structure without changing its external behavior - Martin FowlerVerify no change in external behavior byTestingUsing the right tool (IDE)Formal code analysis by toolCode review or pair programmingBeing very, very careful
Prerequisites for SuccessSafety netEverybody agreed “Collective code ownership”Common understanding of refactoring methodsSupportive environmentPowerful IDE
Refactoring CycleFind smellSelect refactoringApply refactoringRun all tests
3 Ways to Start
Find Something to Improve
Make Static Analysis
Find Smell
How to Find Smell
Smells
Main GoalsOrganizing dataComposing methodsMaking methods calls simplerMoving features between objectsSimplifying conditional expressionDealing with generalizations
Operations Associated with RefactoringReplaceExtractMoveChangeIntroduceRemovePullConsolidatePushInlineAdd
When to Refactor?When add new functionalityRefactor existing code until you understand itRefactor the design to make it simple to addWhen try to find bugsRefactor to understand the codeDuring code reviewsImmediate effect of code reviewAllows for higher level suggestions
Key Elementsof RefactoringSimplifying complex statementsAbstracting common solutions into reusable codeRemoval of duplicate code
Refactoring Techniques
6 Techniques in Action
Extract Methodvoid printOwing() {printBanner();   //print detailsSystem.out.println("name:	" + _name);System.out.println("amount	" + getOutstanding());}void printOwing() {printBanner();printDetails(getOutstanding());}void printDetails (double outstanding) {System.out.println("name:	" + name);System.out.println("amount	" + outstanding);}
Extract Super Class
Decompose Conditionalif (date.before (SUMMER_START) || date.after(SUMMER_END)) {    charge = quantity * winterRate+ serviceCharge;} else {     charge = quantity * summerRate;}if (notSummer(date)) {    charge = winterCharge(quantity);} else {  charge = summerCharge (quantity);}
Replace Error Code with Exceptionboolean withdraw(int amount) {	if (amount > balance)		return false;	else {		balance -= amount;		return true;	}}void withdraw(int amount) throws BalanceException {  if (amount > balance) throw new BalanceException();  balance -= amount;}
Replace Exception with Testdouble getValueForPeriod (int period) {  try {    return values[period];  } catch (ArrayIndexOutOfBoundsException e) {    return 0;  }}double getValueForPeriod (int period) {  return period >= values.length ? 0 : values[period];}
Parameterize Method
Good Design PrinciplesDRYKISSYAGNI
No Silver BulletNeeds lots of practiceRequires disciplineContinuous usageLittle steps
Little steps – huge results
You Need to Pay Technical Debt
Refactoring BenefitsMore readable codeEasier maintenanceCode reuseEasier to add new codeImproved designBetter understandingSpeeding knowledgeEasier to testMinimize duplication 
Live Demo
Questions?

Refactoring

Editor's Notes

  • #7 We need to realize that software must be soft: it has to be easy to change because it will change despite our misguided efforts otherwise.
  • #10 • Make a small change (a single refactoring)• Run all the tests to ensure everything stillworks• If everything works, move on to the nextrefactoring• If not, fix the problem, or undo the change,so you still have a working system
  • #13 Any time you find that you can improve the design of existing codeYou detect a code that smellsAfter static analysis
  • #14 Any time you find that you can improve the design of existing codeYou detect a code that smellsAfter static analysis