Refactoring code in .net

Post on 14-Jan-2017

1.903 views 0 download

Transcript of Refactoring code in .net

Refactoring Code

About me• Nguyen Thanh Tung

• Software architect at MISA JSC

• Microsoft Certified Professional Developer

• Technologies:

• Windows/Windows Phone

• ASP.NET

• XAML/Silverlight

• Windows Forms

• …

• Blog at: http://tungnt.net

• Facebook Page: https://www.facebook.com/tungnt185

• Meetup group: http://www.meetup.com/Ha-Noi-NET-Meetup/

http://tungnt.net

Table of contents• Refactoring General

– What is refactoring?– Who will refactor code?– Why we need refactor code?– When to refactor code?– Where to refactor code?

• How to refactor code?

Refactoring General

http://tungnt.net

What is refactoring?Refactoring means "to improve the design and quality of existing source code without changing its external behavior".

Martin Fowler

Bad Code Good CodeRefactoring

http://tungnt.net

Who will refactor code?• You - Developers

http://tungnt.net

Why we need refactor code?• Code constantly changes and its quality

constantly degrades (unless refactored)• Requirements often change and code

needs to be changed to follow them

http://tungnt.net

When to refactor code?• 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– Implement TDD (Test-Driven-Development)

• Unit tests guarantee that refactoring does not change the behavior– If there are no unit tests, write them

http://tungnt.net

Where to refactor code?• Code smells - certain code structures have possibility of refactoring

• Types of code smells:• Duplicated code• Long method• Large class• Long parameter list• Switch statements• Improper naming• Data members are public• …

How to Refactor code?

http://tungnt.net

Naming• Should be proper, descriptive and

consistent for readability and maintainability

http://tungnt.net

Duplicated code• Violates the DRY (Don’t repeat yourself) principle• Result of copy-pasted code• Solutions: Extract method, extract class, pull-up

method for maintainability

http://tungnt.net

Long MethodExtract method to small methods are always better (easy naming, understanding, less duplicate code)

http://tungnt.net

Conditional complexity• Extract method

http://tungnt.net

Loosely Couple Code• Extract Interface, Extract factory for

extensibility

http://tungnt.net

Return value instead of exception

• Increase performance and readability

http://tungnt.net

Switch statement• Can be replaced with polymorphism for

extensibility

http://tungnt.net

Remove multiple if• Return ASAP (as soon as possible) For

readability

http://tungnt.net

Parameter object• For readability and extensibility

http://tungnt.net

References

http://tungnt.net

References• “Refactoring: Improving the Quality of

Existing Code“ by Telerik Academy• 31 days of refactoring - lostechies.com

http://tungnt.net

Q&A