Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Refactoring

1,295 views

Published on

Essa apresentação fala um pouco sobre o que é, quando e porque aplicar Refatoração em seu código.
Além de mostrar algumas técnicas que Martin Fowler mostra em seu livro.

  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THAT BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book that can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer that is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story That Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths that Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THAT BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { http://bit.ly/2m77EgH } ......................................................................................................................... Download Full EPUB Ebook here { http://bit.ly/2m77EgH } ......................................................................................................................... Download Full doc Ebook here { http://bit.ly/2m77EgH } ......................................................................................................................... Download PDF EBOOK here { http://bit.ly/2m77EgH } ......................................................................................................................... Download EPUB Ebook here { http://bit.ly/2m77EgH } ......................................................................................................................... Download doc Ebook here { http://bit.ly/2m77EgH } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book that can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer that is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story That Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths that Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THAT BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { http://bit.ly/2m77EgH } ......................................................................................................................... Download Full EPUB Ebook here { http://bit.ly/2m77EgH } ......................................................................................................................... Download Full doc Ebook here { http://bit.ly/2m77EgH } ......................................................................................................................... Download PDF EBOOK here { http://bit.ly/2m77EgH } ......................................................................................................................... Download EPUB Ebook here { http://bit.ly/2m77EgH } ......................................................................................................................... Download doc Ebook here { http://bit.ly/2m77EgH } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book that can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer that is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story That Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths that Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THAT BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book that can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer that is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story That Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths that Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Refactoring

  1. 1. Refactoring Bruno Lui @bruno_lui
  2. 2. O que éRefactoring?
  3. 3. “Processo de alterar e melhorar o códigode um software de maneira que seu comportamento não seja alterado”
  4. 4. “Uma maneira disciplinada delimpar código, que minimiza as chances de introduzir bugs”
  5. 5. Porque refatorar ?
  6. 6. Para melhorar odesign do código existenteevitando que elefique decadente..
  7. 7. Para ajudar aencontrar bugs..
  8. 8. Para tornar o código mais fácil de entender..
  9. 9. Para tornar o código maisbarato e rápido de modificar
  10. 10. Quando começamos a mergulhar no código ruim, logodescobrimos várias “oportunidades” para refatorá-lo...
  11. 11. E quanto mais fundo vamos, mais dessas “opotunidades” aparecem..aumentando nossa vontade de alterar...
  12. 12. Antes de começar a cavar a própria cova, saiba que...
  13. 13. A Refatoraçãodeve ser uma práticasistemática e disciplinada.
  14. 14. Quando refatorar ?
  15. 15. Quando vamos adicionar uma nova funcionalidadeO código que deve ser alterado está difícil de entender.O design não ajuda a adicionara nova funcionalidade facilmente
  16. 16. Quando vamos corrigir um bugUm bug reportado pode ser umsinal que o código não estava claroo bastante para evitá-lo.
  17. 17. Quando vamos revisar o código de alguém O código pode parecer limpo para mim, mas não para minha equipe.Sugestões podem ajudara melhorar o código.
  18. 18. "Decidir quando começar e quando parar uma refatoração, é tão importante quanto saber como fazê-la."
  19. 19. Quando não refatorarMuitas aplicações estão totalmente acopladas ao banco de dados. Quando um código estiver tão cheio de bugs ou com um design muito ruim, é melhor começar do zero.
  20. 20. Primeiro passo...Criar um conjunto de testes sólidospara garantir que sua refatoraçãonão quebre o código que estáfuncionando.
  21. 21. Técnicas derefatoração
  22. 22. Extract MethodTransformar um trecho de código em um novo método. O seu nome deve explicar seu propósito. Muitos problemas vêm de métodos muito grandes e com muita informação.
  23. 23. Remove temp with queryQuando transformamos uma variável temporária usada para guardar o resultado de uma expressão em um método.
  24. 24. double precoBase = quantidade * preco;if (precoBase > 1000) { return precoBase * 0.95;} else { return precoBase * 0.98;} if (precoBase() > 1000) { return precoBase() * 0.95; } else { return precoBase() * 0.98; } double precoBase() { return quantidade * preco; }
  25. 25. Move method/field Mover um método/atributo quando é ou será usado em outras classes além da classe em que está definido.Métodos: Crie um novo método com o mesmo corpo na classemais usada, e apenas delegue a chamada do método antigo para onovo.Atributos: Crie um novo atributo em outra classe e use oencapsulamento para delegar.
  26. 26. Extract class Quando uma classe está fazendo o trabalho de duas.class Person { class Person { String name; String name; String officeAreaCode; ... String officeNumber; TelephoneNumber officePhone; ... }} class TelephoneNumber { String areaCode; String number; }
  27. 27. Hide delegateRemova a dependência de uma classe que possua um delegate para um atributo de outra classe.
  28. 28. class Pessoa { class Pessoa { Departamento departamento; Departamento departamento; public Departamento getDepartamento(){ public Pessoa getGerente() { return departamento; return departamento.getGerente(); } }} }class Departamento { private Pessoa gerente; public Pessoa getGerente() { return gerente; }} gerente = joao.getDepartamento().getGerente(); gerente = joao.getGerente();
  29. 29. Remove middle man O contrário do Hide Delegate. Crie um método para acessar o atributo encapsulado.Quando há muitos atributos na classe delegate e você precisaficar criando novos métodos toda vez.
  30. 30. Replace data value with objectQuando um item que precisa de um comportamento adicional Order Order _________________ 1 customer: String Customer _________________ name: String
  31. 31. Encapsulate Collection Quando somente temos o método para retornar a collection imutável. Criamos métodos para adicionar e remover elementos. PersonPerson __________________________________ getCourses():Unmodifiable SetgetCourses():Set addCourse(:Course)setCourses(:Set) removeCourse(:Course)
  32. 32. Decompose Conditional Uma lógica condicional não muito legível aumenta a complexidade.Pode facilmente nos confundir e alterar o comportamento desejado.
  33. 33. Decompose Conditionalif (date.before(SUMMER_START) || date.after(SUMMER_END)) { charge = quantity * winterRate + winterSeviceCharge;} else { charge = quantity * summerRate;}if (notSummer(date)) { charge = winterCharge(quantity);} else { charge = summerCharge(quantity);}
  34. 34. Consolidate Duplicate conditional fragments Quando temos o mesmo trecho de código dentro de uma lógica condicional. Mova-o para fora da lógica.
  35. 35. Consolidate Duplicate conditional fragments if (isSpecial()) { total = price * 0.95; send(); } else { total = price * 0.98; send(); } if (isSpecial()) { total = price * 0.95; } else { total = price * 0.98; } send();
  36. 36. Separate query from modifierQuando o mesmo método retorna um valor e altera o estado de um objeto. Separe-o em dois métodos. Customer __________________________________ getTotalOutstandingAndSetReadyForSummaries Customer _________________ getTotalOutstanding setReadyForSummaries
  37. 37. Parameterize MethodVários métodos fazem coisas parecidas mas com valores diferentes. Unifique o método e parametrize o valor. Employee Employee _________________ _________________ fivePercentRaise() raise(percentage) tenPercentRaise()
  38. 38. Preserve whole objectQuando usamos vários valores de um objeto para passá-los para outro método. Passe o objeto inteiro por parametro. int low = period.getLow(); int high = period.getHigh(); withinPlan = plan.withinRange(low, high); withinPlan = plan.withinRange(period);
  39. 39. Martin Fowler
  40. 40. “Qualquer idiota consegue escrevercódigo que o computador entenda...
  41. 41. ...mas só bonsprogramadores conseguemescrever código que outras pessoas entendam.”
  42. 42. Referências http://www.slideshare.net/gvespucci/refactoring-an-introduction http://www.slideshare.net/redigon/refactoring-1658371 Imagenshttp://www.flickr.com/photos/68751915@N05/6848823919http://www.flickr.com/photos/raiderslight/2800096351/http://theassistant.files.wordpress.com/2009/11/013.jpghttp://www.flickr.com/photos/birminghamcityuniversity/5367360800/http://1.bp.blogspot.com/_9iN8wXq1y_s/TOF3u11KD1I/AAAAAAAAAEg/v3HOYSzJlzo/s1600/why2.jpghttp://greatmiddleway.files.wordpress.com/2012/03/doubt1.jpghttp://www.sxc.hu/photo/1133804http://tweakyourbiz.com/growth/files/reviews.jpghttp://torwars.com/wp-content/uploads/2012/01/patch-notes-and-bug-fixes-SWTOR.pnghttp://www.revenuewoo.com/wp-content/uploads/2012/05/BlogUpp_new_features-788925.jpg
  43. 43. Obrigado!

×