SlideShare a Scribd company logo
Refactoring
What is Refactoring?
Refactoring is a disciplined
technique for restructuring
an existing body of code,
altering its internal
structure without changing
its external behavior.
Martin Fowler
Refactoring, improving design of existing code
Refactoring
Refactoring
What happened?
Sharepoint?
Lack of time?
Lack of skill?
Poor management?
Text
Why Refactor?
Any fool can write code that
a computer can understand.
Good programmers write code
that humans can understand
Martin Fowler
Remove duplication
Remove duplication
Remove duplication
Make code
maintainable
Make code readable
(by humans)
Spaghetti Code
Technical Debt
Improve Design
Reduce BLOC
(beers x LOC)
When to Refactor?
Fixing bugs
Adding features
Code Review
Manager on Vacation?
100% sure the new
code is better
Cost Not to Refactor
greater than
Cost to Refactor
Cost = Doing the change
+ Testing it
+ Documentation
Risk of
Introducing bugs
Refactoring
Refactoring
Only refactor if you
are confident

(it works as before, no side effects)
Unit Tests
One class
One method
No dependencies
(mocks)
Hard to do
with Legacy Code
Core of TDD
Integration Tests
More than
one class
Communication
between
components
Acceptance tests
Black box testing
End to end
Given input
When doing YYY
Expect output
Works with
Legacy Code
Works with
New Code
Works with
-40!!!
Core of BDD
How to Refactor?
Refactoring
Refactoring
Code should be clear
Like telling a story
Refactoring
algorithm
Te
x

M
et
ho

t

d?
Second
Write a test for it
Third
Make it better
Fourth
Run the tests
Repeat until
out of coffee
Nesting Conditionals
C#

public double SomeMethod()
{
var result = 0d;
if (_firstGuard)
{
result = FirstCalculation();
if (_secondGuard)
{
result = SecondCalculation();
}
}
return result;
}
C#

RE

public double BetterMethod()
{
if (!_firstGuard)
{
return 0;
}
if (!_secondGuard)
{
return FirstCalculation();
}
return SecondCalculation();
}

FAC
TO
R

ED
Ruby

class NestedCalculation
def awesome_method
first_calculation
||
second_calculation ||
default_calculation
end
def first_calculation
@first_guard && some_calc_here
end
def second_calculation
# etc...
end
end

RE

FAC
TO
R

ED
C#

public double SomeMethod()
{
var result = 0d;
if (_guard1)
{
if (_guard2)
{
if (_guard3)
{
result = Calc1() + Calc2();
}
}
}
return result;
}
C#

public double BetterMethod()
{
if (_guard1 && _guard2 && _guard3)
{
return Calc1() + Calc2();
}
return 0;
}

RE

FAC
TO
R

ED
C#

public bool SomeMethod()
{
var result = false;
if (_firstGuard)
{
if (_secondGuard)
result = true;
}
else
result = true;
return result;
}
C#

RE

public bool BetterMethod()
{
return !_firstGuard || _secondGuard;
}

FAC
TO
R

ED
Functional
Inspiration
DRY
Stop writing
custom loops
Meaning rulez
Java

public Iterable<String> deploy(
Iterable<String> collection) {
Collection<String> result = new ArrayList<>...;
Iterator<String> cursor = collection.iterator();
while(cursor.hasNext()) {
result.add("Deployed to " + cursor.next());
}
return result;
}
Java

public Iterable<String> betterDeploy(
Iterable<String> environments) {

RE

FAC
TO
R

return with(environments)
.convert(new DeployConverter());
}
class DeployConverter
implements Converter<String, String> {
public String convert(String env) {
return "Deployed to " + env;
}
}

ED
Scala

RE

FAC
TO
R

def betterDeploy(environments: Iterable[String])
: Iterable[String] {
environment.map env => s"Deploy to $env"
}

ED
Java

public class Movie {
private String title;
private int review;
public Movie(String title, int review) {
this.title = title;
this.review = review;
}
public String getTitle() {...}
public int getReview() {...}
}
Java

@Test
public void whereAreMyPostIt() {

RE

FAC
TO
R

ED

// arrange
Iterable<Movie> movies = asList(
new Movie("Blazing Saddles", 5), new Movie("Terminator"),
new Movie("Canadian Bacon", 8)
);
// act
Iterable<Movie> reviewed =
filter(having(on(Movie.class).getReview(), greaterThan(-1))
, movies);
// assert
assertThat(joinFrom(reviewed).getTitle(),
equalTo("Blazing Saddles, Canadian Bacon"));
}
Java

@Test
public void wheresMyGanttChart() {

RE

FAC
TO
R

ED

// arrange
Iterable<Movie> movies = asList(new Movie("Blazing Saddles"),
new Movie("Terminator"), new Movie("Curator"));
// act
Matcher<Movie> endsWithAtor = new Predicate<Movie>() {
public boolean apply(Movie item) {
return item.getTitle().endsWith("ator");
}
};
Iterable<Movie> actual = filter(endsWithAtor, movies);
// assert
assertThat(joinFrom(actual).getTitle(),
equalTo("Terminator, Curator"));
}
C#

public int Mysterious(IEnumerable<int> collection)
{
return collection.Aggregate((a, b) => a + b);
}
Coffee

[1..1000].reduce (t, s) -> t + s
What about
MONADS?
Just kidding :)
Don’t forget OOP
Abstraction is
KEY
Refactoring
Coffee

class BudgetViewModel
constructor: (json) ->
@budgets
= [2013, 2012, 2011]
@budgetIndex = 0
salary: ->
return 5000 if @budgetIndex == 0
return 2000 if @budgetIndex == 1
1000
Coffee

RE

class BudgetViewModel
constructor: ->
@budgets = [
new BudgetModel(2013, 5000),
new BudgetModel(2012, 2000),
new BudgetModel(2011, 1000)
]
@budget = @budgets[0]
salary: => @budget.salary

FAC
TO
R

ED
Coffee
KO

class BudgetViewModel

RE

FAC
TO
R

constructor: ->
@budgets = ko.observableArray [
new BudgetModel(2013, 5000),
new BudgetModel(2012, 2000),
new BudgetModel(2011, 1000)
]
@budget = ko.observable()
@salary = ko.computed => @budget().salary

ED
Language is your friend
(or it should be)
The right tool
for the job
Coffee

class window.NewsViewModel
constructor: (@limit = -1) ->
@news = ko.observableArray()
@title = ko.observable()
$.getJSON '../api/news', @loadNews
loadNews: (data) =>
max = (if @limit == -1 then -1 else @limit - 1)
@news(@createNewsItem(e) for e in data[0..max])
@title @news()[0]?.Title
createNewsItem: (e) =>
newsItem =
Title: e.Title
Date: @parseDate(e.Date)
Body: e.Body
JS
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
window.NewsViewModel = (function() {
function NewsViewModel(limit) {
this.limit = limit != null ? limit : -1;
this.createNewsItem = __bind(this.createNewsItem, this);
this.loadNews = __bind(this.loadNews, this);
this.news = ko.observableArray();
this.title = ko.observable();
$.getJSON('../api/news', this.loadNews);
}
NewsViewModel.prototype.loadNews = function(data) {
var e, max, _ref;
max = (this.limit === -1 ? -1 : this.limit - 1);
this.news((function() {
var _i, _len, _ref, _results;
_ref = data.slice(0, max + 1 || 9e9);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
e = _ref[_i];
_results.push(this.createNewsItem(e));
}
return _results;
}).call(this));
return this.title((_ref = this.news()[0]) != null ? _ref.Title : void 0);
};
NewsViewModel.prototype.createNewsItem = function(e) {
var newsItem;
return newsItem = {
Title: e.Title,
Date: this.parseDate(e.Date),
Body: e.Body
};
};
return NewsViewModel;
})();
}).call(this);
JVM supports
multiple languages
same for
.net framework
Tests are a great
place to start
Thank you!
amir@barylko.com
@abarylko
http://bit.ly/abarylkop
Books
Books
Photo Credit
•

Under http://creativecommons.org/licenses/by/2.5/

•
•

Bill Ward, Derek Schin's Trucks 1, http://flic.kr/p/m5L5S

•

Jeremy Keith, Roast beef, http://flic.kr/p/TKUz

•

Rob Campbell, Field of daisies, http://flic.kr/p/6QJjU4

•

•

Joe Cheng, DSC_7820-01, http://flic.kr/p/2Zt2u

Karin Dalziel, The Thinker, http://flic.kr/p/4UYArc

Under http://creativecommons.org/licenses/by-sa/3.0/us/

•

Derick Bailey, SOLID Motivational Posters, http://bit.ly/17aVaHg
Photo Credit 2
•
•

How to write good code, http://xkcd.com/844/
Understanding flow charts, http://lifehacker.com/5909501/how-tochoose-the-best-chart-for-your-data
Resources
•
•

http://www.infoq.com/news/2010/06/decision-to-refactor

•
•
•

Refactoring Catalog: http://www.refactoring.com/catalog/

http://stackoverflow.com/questions/38635/what-static-analysis-toolsare-available-for-c

LambdaJ: https://code.google.com/p/lambda
Coffeescript: http://coffeescript.org/

More Related Content

PDF
Refactoring
PPT
Test driven development_for_php
PPTX
Typescript barcelona
PDF
Effective Java with Groovy - How Language Influences Adoption of Good Practices
PPTX
Typed? Dynamic? Both! Cross-platform DSLs in C#
PPTX
Firebase ng2 zurich
PDF
API first with Swagger and Scala by Slava Schmidt
PDF
JavaScript Functions
Refactoring
Test driven development_for_php
Typescript barcelona
Effective Java with Groovy - How Language Influences Adoption of Good Practices
Typed? Dynamic? Both! Cross-platform DSLs in C#
Firebase ng2 zurich
API first with Swagger and Scala by Slava Schmidt
JavaScript Functions

What's hot (20)

PDF
Functional Javascript
PDF
A Blueprint for Scala Microservices
PPTX
LinkedIn TBC JavaScript 100: Functions
PPTX
Java script
KEY
Solid principles
PDF
Currying and Partial Function Application (PFA)
PDF
QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"
PPTX
Introduction to nsubstitute
PDF
Graphql, REST and Apollo
PDF
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
PDF
Intro to GraphQL on Android with Apollo DroidconNYC 2017
PDF
Why is crud a bad idea - focus on real scenarios
PDF
Leveraging Completable Futures to handle your query results Asynchrhonously
PDF
JavaScript Refactoring
PPT
JavaScript Functions
KEY
Unit testing zend framework apps
PPT
DSLs In Erlang
PDF
Nativescript angular
PDF
"Inside The AngularJS Directive Compiler" by Tero Parviainen
PPTX
Rspec 101
Functional Javascript
A Blueprint for Scala Microservices
LinkedIn TBC JavaScript 100: Functions
Java script
Solid principles
Currying and Partial Function Application (PFA)
QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"
Introduction to nsubstitute
Graphql, REST and Apollo
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
Intro to GraphQL on Android with Apollo DroidconNYC 2017
Why is crud a bad idea - focus on real scenarios
Leveraging Completable Futures to handle your query results Asynchrhonously
JavaScript Refactoring
JavaScript Functions
Unit testing zend framework apps
DSLs In Erlang
Nativescript angular
"Inside The AngularJS Directive Compiler" by Tero Parviainen
Rspec 101
Ad

Viewers also liked (8)

PDF
YEG-Agile-planning
PDF
Agile requirements
PDF
PRDCW-advanced-design-patterns
PDF
Agile planning
PDF
agile-planning
PDF
C++ L07-Struct
PDF
C++ L02-Conversion+enum+Operators
PDF
sdec11-Advanced-design-patterns
YEG-Agile-planning
Agile requirements
PRDCW-advanced-design-patterns
Agile planning
agile-planning
C++ L07-Struct
C++ L02-Conversion+enum+Operators
sdec11-Advanced-design-patterns
Ad

Similar to Refactoring (20)

PPTX
Code Refactoring
PPT
Refactoring Tips by Martin Fowler
PDF
Refactoring
PDF
Keeping code clean
PPT
TDD And Refactoring
PPTX
Agile korea 2013 유석문
ODP
New Ideas for Old Code - Greach
PDF
Code refactoring workshop (in Javascript)
PDF
Refactoring 2 The Max
PDF
Introduction to Refactoring
PPTX
Refactoring workshop
PDF
Patterns, Code Smells, and The Pragmattic Programmer
PPTX
Code refactoring
PDF
Refactoring 2TheMax (con ReSharper)
PPT
Cómo Java afecta nuestros Diseños
PPTX
Refactoring
PPTX
Code reviews
PDF
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
PDF
Functional Programming 101 for Java 7 Developers
PDF
functional groovy
Code Refactoring
Refactoring Tips by Martin Fowler
Refactoring
Keeping code clean
TDD And Refactoring
Agile korea 2013 유석문
New Ideas for Old Code - Greach
Code refactoring workshop (in Javascript)
Refactoring 2 The Max
Introduction to Refactoring
Refactoring workshop
Patterns, Code Smells, and The Pragmattic Programmer
Code refactoring
Refactoring 2TheMax (con ReSharper)
Cómo Java afecta nuestros Diseños
Refactoring
Code reviews
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
Functional Programming 101 for Java 7 Developers
functional groovy

More from Amir Barylko (20)

PDF
Functional converter project
PDF
Elm: delightful web development
PDF
Dot Net Core
PDF
No estimates
PDF
User stories deep dive
PDF
Coderetreat hosting training
PDF
There's no charge for (functional) awesomeness
PDF
What's new in c# 6
PDF
Productive teams
PDF
Who killed object oriented design?
PDF
From coach to owner - What I learned from the other side
PDF
Communication is the Key to Teamwork and productivity
PDF
Acceptance Test Driven Development
PDF
Agile requirements
PDF
Agile teams and responsibilities
PDF
Beutiful javascript with coffeescript
PDF
Sass & bootstrap
PDF
Rich UI with Knockout.js &amp; Coffeescript
PDF
SDEC12 Beautiful javascript with coffeescript
PDF
Beutiful javascript with coffeescript
Functional converter project
Elm: delightful web development
Dot Net Core
No estimates
User stories deep dive
Coderetreat hosting training
There's no charge for (functional) awesomeness
What's new in c# 6
Productive teams
Who killed object oriented design?
From coach to owner - What I learned from the other side
Communication is the Key to Teamwork and productivity
Acceptance Test Driven Development
Agile requirements
Agile teams and responsibilities
Beutiful javascript with coffeescript
Sass & bootstrap
Rich UI with Knockout.js &amp; Coffeescript
SDEC12 Beautiful javascript with coffeescript
Beutiful javascript with coffeescript

Recently uploaded (20)

PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Spectroscopy.pptx food analysis technology
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
cuic standard and advanced reporting.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
sap open course for s4hana steps from ECC to s4
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Empathic Computing: Creating Shared Understanding
Reach Out and Touch Someone: Haptics and Empathic Computing
20250228 LYD VKU AI Blended-Learning.pptx
Review of recent advances in non-invasive hemoglobin estimation
“AI and Expert System Decision Support & Business Intelligence Systems”
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Per capita expenditure prediction using model stacking based on satellite ima...
Spectroscopy.pptx food analysis technology
Spectral efficient network and resource selection model in 5G networks
Network Security Unit 5.pdf for BCA BBA.
cuic standard and advanced reporting.pdf
Approach and Philosophy of On baking technology
sap open course for s4hana steps from ECC to s4

Refactoring