When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation www.telerik.com Senior Developer and Team Leader.

Slides:



Advertisements
Similar presentations
Windows Basic and Dynamic Disk Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator Marian Marinov CEO of 1H Ltd.
Advertisements

HTML Forms, GET, POST Methods Tran Anh Tuan Edit from Telerik Academy
Make swiftly iOS development Telerik Academy Telerik Academy Plus.
Amazon S 3, App Engine Blobstore, Google Cloud Storage, Azure Blobs Svetlin Nakov Telerik Software Academy academy.telerik.com.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
Telerik School Academy ASP.NET MVC.
Shortest paths in edge-weighted digraph Krasin Georgiev Technical University of Sofia g.krasin at gmail com Assistant Professor.
Telerik Software Academy Telerik School Academy.
Asynchronous Programming with C# and WinRT
Telerik School Academy ASP.NET MVC.
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Hybrid or Native?! Doncho Minkov Telerik Software Academy Senior Technical Trainer
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
Processing Sequences of Elements Telerik School Academy C# Fundamentals – Part 1.
With Mocha and Karma Telerik Academy Telerik Software Academy.
C# Fundamentals – Part I
The Business Plan and the Business Model Margarita Antonova Volunteer Telerik Academy academy.telerik.com Business System Analyst Telerik Corporation.
What are ADTs, STL Intro, vector, list, queue, stack Learning & Development Team Telerik Software Academy.
Making JavaScript code by template! Learning & Development Team Telerik Software Academy.
Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training Who, What, Why?
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Processing Matrices and Multidimensional Tables Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Learning & Development Telerik Software Academy.
Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Telerik Software Academy ASP.NET Web Forms.
Classical OOP in JavaScript Classes and stuff Telerik Software Academy
Optimization problems, Greedy Algorithms, Optimal Substructure and Greedy choice Learning & Development Team Telerik Software.
Using Selenium for Mobile Web Testing Powered by KendoUI Telerik QA Academy Atanas Georgiev Senior QA Engineer KendoUI Team.
New features: classes, generators, iterators, etc. Telerik Academy Plus JavaScript.Next.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
When and How to Refactor? Refactoring Patterns Telerik Software Academy High-Quality Code.
Loops, Conditional Statements, Functions Tran Anh Tuan Edit from Telerik Academy
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
Course Introduction Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Telerik Software Academy End-to-end JavaScript Applications.
General and reusable solutions to common problems in software design Vasil Dininski Telerik Software Academy academy.telerik.com Intern at Telerik Academy.
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Pavel Kolev Telerik Software Academy Senior.Net Developer and Trainer
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
Improving the Quality of Existing Code Svetlin Nakov Telerik Corporation
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Doing the Canvas the "easy way"! Learning & Development Telerik Software Academy.
Creating and Running Your First C# Program Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Course Overview Doncho Minkov Telerik Software Academy Technical Trainer
REFACTORINGREFACTORING. Realities Code evolves substantially during development Requirements changes 1%-4% per month on a project Current methodologies.
Subroutines in Computer Programming Telerik School Academy C# Fundamentals – Part 1.
Revealing the Secrets of Self-Documenting Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer.
Correctly Formatting the Source Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Data Types, Primitive Types in C++, Variables – Declaration, Initialization, Scope Telerik Software Academy academy.telerik.com Learning and Development.
The past, the present, the future Learning & Development Team Telerik Software Academy.
Learn to Design Error Steady Code Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.
Telerik JavaScript Framework Telerik Software Academy Hybrid Mobile Applications.
Building Rock-Solid Software Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Telerik Software Academy Databases.
Things start to get serious Telerik Software Academy JavaScript OOP.
Learning & Development Mobile apps for iPhone & iPad.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
Inheritance, Abstraction, Encapsulation, Polymorphism Telerik Software Academy Mobile apps for iPhone & iPad.
Mocking tools for easier unit testing Telerik Software Academy High Quality Code.
What why and how? Telerik School Academy Unity 2D Game Development.
Windows Security Model Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator
Presentation transcript:

When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader

 It is a step by step process that turns the bad code into good code  Based on "refactoring patterns"  well-known recipes for improving the code 2 Refactoring means "to improve the design and quality of existing source code without changing its external behavior". Martin Fowler

 What is refactoring of the source code?  Improving the design and quality of existing source code without changing its behavior  Step by step process that turns the bad code into good code (if possible)  Why we need refactoring?  Code constantly changes and its quality constantly degrades (unless refactored)  Requirements often change and code needs to be changed to follow them 3

 Bad smells in the code indicate need of refactoring  Refactor when you  Add a new method or class  Fix an existing bug  Reviewing someone else’s code  Unit tests guarantee that refactoring does not change the behavior  If there are no unit tests, write them 4

 Duplicated code  Long method  Large class  Long parameter list  Switch statements  Temporary field  Bad comments / comments for bad code  Improper naming  Data members are public 5

 Global variables  Overused primitives  Divergent change  Shotgun surgery  Feature envy  Middle man  Speculative generality  Inappropriate Intimacy 6

 Replace a magic number with a named constant  Rename a variable with more informative name  Replace an expression with a method  Introduce an intermediate variable  Convert a multi-use variable to a multiple single- use variables  Convert a data primitive to a class  Change an array to an object  Encapsulate a collection 7

 Decompose a boolean expression  Move a complex boolean expression into a well-named boolean function  Return as soon as you know the answer instead of assigning a return value (?)  Use break or return instead of a loop control variable  Replace conditionals with polymorphism 8

 Extract method  Inline method  Add / remove parameter  Combine similar methods by parameterizing them  Separate methods whose behavior depends on parameters passed in  Pass a whole object rather than specific fields  Encapsulate downcast 9

 Change structure to class and vice versa  Replace virtual routines with data initialization  Pull members up / push members down the hierarchy  Extract specialized code into a subclass  Combine similar code into a superclass 10

 Move a method to another class  Convert a class to two  Delete a class  Hide a delegating class  Remove the man in the middle  Introduce (use) an extension class  Encapsulate an exposed member variable 11

 Move class (set of classes) to another namespace  Provide a factory method instead of a simple constructor  Replace error codes with exceptions  Extract strings to resource files 12

 Save the code you start with  Make sure you have tests to assure the behavior after the code is refactored  Do refactorings one at a time  Keep refactorings small  Check-in and test often  Don’t underestimate small changes 13

Well-Known Recipes for Improving the Code Quality

 When should we perform refactoring of the code?  Bad smells in the code indicate need of refactoring  Unit tests guarantee that refactoring does not change the behavior  Rafactoring patterns  Large repeating code fragments  e xtract repeating code in separate method  Large methods  split them logically  Large loop body or deep nesting  extract method 15

 Refactoring patterns  Class or method has weak cohesion  split into several classes / methods  Single change carry out changes in several classes  classes have tight coupling  consider redesign  Related data are always used together but are not part of a single class  group them in a class  A method has too many parameters  create a class to groups parameters together  A method calls more methods from another class than from its own class  move it 16

 Refactoring patterns  Two classes are tightly coupled  merge them or redesign them to separate their responsibilities  Public non-constant fields  make them private and define accessing properties  Magic numbers in the code  consider extracting constants  Bad named class / method / variable  rename it  Complex boolean condition  split it to several expressions or method calls 17

 Refactoring patterns  Complex expression  split it into few simple parts  A set of constants is used as enumeration  convert it to enumeration  Method logic is too complex and is hard to understand  extract several more simple methods or even create a new class  Unused classes, methods, parameters, variables  remove them  Large data is passed by value without a good reason  pass it by reference 18

 Refactoring patterns  Few classes share repeating functionality  extract base class and reuse the common code  Different classes need to be instantiated depending on configuration setting  use factory  Code is not well formatted  reformat it  Too many classes in a single namespace  split classes logically into more namespaces  Unused using definitions  remove them  Non-descriptive error messages  improve them  Absence of defensive programming  add it 19

Live Demo

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране

 Refactor the C# code from the Visual Studio Project "12. Refactoring-Homework.zip" to improve its internal quality. You might follow the following steps: 12. Refactoring-Homework.zip12. Refactoring-Homework.zip 1.Make some initial refactorings like:  Reformat the code.  Rename the ugly named variables. 2.Make the code testable.  Think how to test console-based input / output. 3.Write unite tests. Fix any bugs found in the mean time. 4.Refactor the code following the guidelines from this chapter. Do it step by step. Run the unit tests after each major change. 22

 C# Telerik Academy  csharpfundamentals.telerik.com csharpfundamentals.telerik.com  Telerik Software Academy  academy.telerik.com academy.telerik.com  Telerik Facebook  facebook.com/TelerikAcademy facebook.com/TelerikAcademy  Telerik Software Academy Forums  forums.academy.telerik.com forums.academy.telerik.com