SlideShare a Scribd company logo
1 of 16
Refactoring and Code Smells
Dino Esposito
Smells and 7 Gold Virtues
 Code smells
 The Simple Case of Special Strings
 Join Data that Want to Go Together
 Readability
 Every class begins with a “new”
 Let’s talk dependency injection
 Null pointers
 You Ain’t Gonna Use It
Code Smells
 In software, a code smell is not pleasant
 Should we be worried about code odor?
 A code smell is not the same as a bug
 It’s a piece of code that we perceive as not right, but don’t fix right away
 Code smells affect the maintainability of a software system
 Any code is almost immediately in need of maintenance as soon as it’s written
Code Smells
 Method-level Code Smells
 Class-level Code Smells
 General Code Smells

Method-level Code Smells
• Dead code
• Lazy method
• Middle man
• God method
• Long parameters list
• Contrived complexity
• Cyclomatic complexity
• Inappropriate intimacy
• Feature envy
• Black sheep
Class-level Code Smells
• Lazy object
• Middle man
• God method
• Primitive obsession
• Tell-don’t-ask
• Indecent exposure
• Inappropriate intimacy
• Refused bequest
• Speculative generality
• Temporary field
General Code Smells
• Lost intent
• Oddball solution
• Combinatorial explosion
• Duplicated code
• Contrived complexity
• Solution sprawl
• Divergent change
• Shotgun surgery
• Deodorant comments
• Data clumps
The Simple Case of Special Strings
• “Value Object”
• No identity
• Represented by the
data it holds
• Close to real-world
public class Email
{
public Email(string email)
{
if (string.IsNullOrWhiteSpace(email))
throw new InvalidDataException();
Address = email;
}
public string Address { get; }
public string GetServer()
{
var index = Address.IndexOf("@", StringComparison.Ordinal);
return index > 0
? Address.Substring(0, index)
: Address;
}
}
The Simple Case of Special Strings
• “Value Object”
• No identity
• Represented by the
data it holds
• Close to real-world
public class Email
{
public Email(string email)
{
if (string.IsNullOrWhiteSpace(email))
throw new InvalidDataException();
Address = email;
}
public string Address { get; }
public string GetServer()
{
var index = Address.IndexOf("@", StringComparison.Ordinal);
return index > 0
? Address.Substring(0, index)
: Address;
}
}
Join Data that Want to Go Together
Readability
 ToString method
 Extension methods
 Fixed sets of values (enums, const, ad hoc classes)
 Avoid queries, primitives, hide checks in aptly named methods
var editMode = (request.Id > 0);
var editMode = request.IsInEditMode();
Every Class Begins with a “new”
 Constructors are natural to use as everyone learns object-oriented
programming from constructors, but they are hardly business-specific
 In DDD, you only create instances if you have a business reason
 Factory methods make it easier
 Stay closer to the ubiquitous language of the business domain,
 If too many static methods, group your factory methods into an
embedded factory class.
Dependency Injection
 Loosely coupled code is not code that works in a standalone context or
in a disconnected software island
 Loosely coupled code is simply code where connections exist, but are
strictly ruled and occur under the umbrella of clear contracts
 Service Locator vs. Dependency Injection
 IoC framework just make DI simpler (much simpler)
Null Pointers
 Null checking is boring and doubtless every developer will find a way
to forget one at some point
 “My billion-dollar mistake” said Sir Hoare, inventor of Quicksort
 The main issue with null references is that once the language allows
references to be null, well, any reference can find its way to be null
 Nullability in C# (only value types) and Kotlin (any type)
 Native syntax for safe calls (also in C#)
 Null doesn’t refer to any domain-specific state
 In any business ubiquitous language there’s nothing like null, like a non-value
You Ain’t Gonna Need It
 Unreachable code
 Detected by smart editors
 In order to improve readability dead code should be investigated and
eliminated if it’s dead beyond any reasonable doubt
 “Commented out code always work” (cit.)
 Unused branches, but also includes unused parameters in used
methods, unused variables, and private methods never invoked
 Have a smart tool to help you
 In large codebases is a great help
Thoughts?

More Related Content

More from NETFest

More from NETFest (20)

.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture
.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture
.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture
 
.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests
.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests
.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests
 
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос....NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
 
.NET Fest 2019. Roberto Freato. Azure App Service deep dive
.NET Fest 2019. Roberto Freato. Azure App Service deep dive.NET Fest 2019. Roberto Freato. Azure App Service deep dive
.NET Fest 2019. Roberto Freato. Azure App Service deep dive
 
.NET Fest 2019. Леонид Молотиевский. DotNet Core in production
.NET Fest 2019. Леонид Молотиевский. DotNet Core in production.NET Fest 2019. Леонид Молотиевский. DotNet Core in production
.NET Fest 2019. Леонид Молотиевский. DotNet Core in production
 
.NET Fest 2019. Александр Демчук. How to measure relationships within the Com...
.NET Fest 2019. Александр Демчук. How to measure relationships within the Com....NET Fest 2019. Александр Демчук. How to measure relationships within the Com...
.NET Fest 2019. Александр Демчук. How to measure relationships within the Com...
 
.NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real...
.NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real....NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real...
.NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real...
 
.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem
.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem
.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem
 
.NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ...
.NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ....NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ...
.NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ...
 
.NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali...
.NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali....NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali...
.NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali...
 
.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET
.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET
.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET
 
.NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur...
.NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur....NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur...
.NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur...
 
.NET Fest 2019. Eran Stiller. 6 Lessons I Learned on My Journey from Monolith...
.NET Fest 2019. Eran Stiller. 6 Lessons I Learned on My Journey from Monolith....NET Fest 2019. Eran Stiller. 6 Lessons I Learned on My Journey from Monolith...
.NET Fest 2019. Eran Stiller. 6 Lessons I Learned on My Journey from Monolith...
 
.NET Fest 2019. Kevin Dockx. Uncovering Swagger/OpenAPI
.NET Fest 2019. Kevin Dockx. Uncovering Swagger/OpenAPI.NET Fest 2019. Kevin Dockx. Uncovering Swagger/OpenAPI
.NET Fest 2019. Kevin Dockx. Uncovering Swagger/OpenAPI
 
.NET Fest 2019. Kevin Dockx. OpenID Connect In Depth
.NET Fest 2019. Kevin Dockx. OpenID Connect In Depth.NET Fest 2019. Kevin Dockx. OpenID Connect In Depth
.NET Fest 2019. Kevin Dockx. OpenID Connect In Depth
 
.NET Fest 2019. Андрей Антиликаторов. Проектирование и разработка Big Data ре...
.NET Fest 2019. Андрей Антиликаторов. Проектирование и разработка Big Data ре....NET Fest 2019. Андрей Антиликаторов. Проектирование и разработка Big Data ре...
.NET Fest 2019. Андрей Антиликаторов. Проектирование и разработка Big Data ре...
 
.NET Fest 2019. Irina Scurtu. Forget about HTTP
.NET Fest 2019. Irina Scurtu. Forget about HTTP.NET Fest 2019. Irina Scurtu. Forget about HTTP
.NET Fest 2019. Irina Scurtu. Forget about HTTP
 
.NET Fest 2019. Łukasz Pyrzyk. Daily Performance Fuckups
.NET Fest 2019. Łukasz Pyrzyk. Daily Performance Fuckups.NET Fest 2019. Łukasz Pyrzyk. Daily Performance Fuckups
.NET Fest 2019. Łukasz Pyrzyk. Daily Performance Fuckups
 
.NET Fest 2019. Андрей Винда. Создание REST API с поддержкой высокой нагрузки
.NET Fest 2019. Андрей Винда. Создание REST API с поддержкой высокой нагрузки.NET Fest 2019. Андрей Винда. Создание REST API с поддержкой высокой нагрузки
.NET Fest 2019. Андрей Винда. Создание REST API с поддержкой высокой нагрузки
 
.NET Fest 2019. Arnon Axelrod. Test automation for developers
.NET Fest 2019. Arnon Axelrod. Test automation for developers.NET Fest 2019. Arnon Axelrod. Test automation for developers
.NET Fest 2019. Arnon Axelrod. Test automation for developers
 

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 

.NET Fest 2018. Dino Esposito. Refactoring and Code Smells

  • 1. Refactoring and Code Smells Dino Esposito
  • 2. Smells and 7 Gold Virtues  Code smells  The Simple Case of Special Strings  Join Data that Want to Go Together  Readability  Every class begins with a “new”  Let’s talk dependency injection  Null pointers  You Ain’t Gonna Use It
  • 3. Code Smells  In software, a code smell is not pleasant  Should we be worried about code odor?  A code smell is not the same as a bug  It’s a piece of code that we perceive as not right, but don’t fix right away  Code smells affect the maintainability of a software system  Any code is almost immediately in need of maintenance as soon as it’s written
  • 4. Code Smells  Method-level Code Smells  Class-level Code Smells  General Code Smells 
  • 5. Method-level Code Smells • Dead code • Lazy method • Middle man • God method • Long parameters list • Contrived complexity • Cyclomatic complexity • Inappropriate intimacy • Feature envy • Black sheep
  • 6. Class-level Code Smells • Lazy object • Middle man • God method • Primitive obsession • Tell-don’t-ask • Indecent exposure • Inappropriate intimacy • Refused bequest • Speculative generality • Temporary field
  • 7. General Code Smells • Lost intent • Oddball solution • Combinatorial explosion • Duplicated code • Contrived complexity • Solution sprawl • Divergent change • Shotgun surgery • Deodorant comments • Data clumps
  • 8. The Simple Case of Special Strings • “Value Object” • No identity • Represented by the data it holds • Close to real-world public class Email { public Email(string email) { if (string.IsNullOrWhiteSpace(email)) throw new InvalidDataException(); Address = email; } public string Address { get; } public string GetServer() { var index = Address.IndexOf("@", StringComparison.Ordinal); return index > 0 ? Address.Substring(0, index) : Address; } }
  • 9. The Simple Case of Special Strings • “Value Object” • No identity • Represented by the data it holds • Close to real-world public class Email { public Email(string email) { if (string.IsNullOrWhiteSpace(email)) throw new InvalidDataException(); Address = email; } public string Address { get; } public string GetServer() { var index = Address.IndexOf("@", StringComparison.Ordinal); return index > 0 ? Address.Substring(0, index) : Address; } }
  • 10. Join Data that Want to Go Together
  • 11. Readability  ToString method  Extension methods  Fixed sets of values (enums, const, ad hoc classes)  Avoid queries, primitives, hide checks in aptly named methods var editMode = (request.Id > 0); var editMode = request.IsInEditMode();
  • 12. Every Class Begins with a “new”  Constructors are natural to use as everyone learns object-oriented programming from constructors, but they are hardly business-specific  In DDD, you only create instances if you have a business reason  Factory methods make it easier  Stay closer to the ubiquitous language of the business domain,  If too many static methods, group your factory methods into an embedded factory class.
  • 13. Dependency Injection  Loosely coupled code is not code that works in a standalone context or in a disconnected software island  Loosely coupled code is simply code where connections exist, but are strictly ruled and occur under the umbrella of clear contracts  Service Locator vs. Dependency Injection  IoC framework just make DI simpler (much simpler)
  • 14. Null Pointers  Null checking is boring and doubtless every developer will find a way to forget one at some point  “My billion-dollar mistake” said Sir Hoare, inventor of Quicksort  The main issue with null references is that once the language allows references to be null, well, any reference can find its way to be null  Nullability in C# (only value types) and Kotlin (any type)  Native syntax for safe calls (also in C#)  Null doesn’t refer to any domain-specific state  In any business ubiquitous language there’s nothing like null, like a non-value
  • 15. You Ain’t Gonna Need It  Unreachable code  Detected by smart editors  In order to improve readability dead code should be investigated and eliminated if it’s dead beyond any reasonable doubt  “Commented out code always work” (cit.)  Unused branches, but also includes unused parameters in used methods, unused variables, and private methods never invoked  Have a smart tool to help you  In large codebases is a great help