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

.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 AutoFixtureNETFest
 
.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# TestsNETFest
 
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос....NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...NETFest
 
.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 diveNETFest
 
.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 productionNETFest
 
.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...NETFest
 
.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...NETFest
 
.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 ecosystemNETFest
 
.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 ...NETFest
 
.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...NETFest
 
.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 .NETNETFest
 
.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...NETFest
 
.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...NETFest
 
.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/OpenAPINETFest
 
.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 DepthNETFest
 
.NET Fest 2019. Андрей Антиликаторов. Проектирование и разработка Big Data ре...
.NET Fest 2019. Андрей Антиликаторов. Проектирование и разработка Big Data ре....NET Fest 2019. Андрей Антиликаторов. Проектирование и разработка Big Data ре...
.NET Fest 2019. Андрей Антиликаторов. Проектирование и разработка Big Data ре...NETFest
 
.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 HTTPNETFest
 
.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 FuckupsNETFest
 
.NET Fest 2019. Андрей Винда. Создание REST API с поддержкой высокой нагрузки
.NET Fest 2019. Андрей Винда. Создание REST API с поддержкой высокой нагрузки.NET Fest 2019. Андрей Винда. Создание REST API с поддержкой высокой нагрузки
.NET Fest 2019. Андрей Винда. Создание REST API с поддержкой высокой нагрузкиNETFest
 
.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 developersNETFest
 

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

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 

Recently uploaded (20)

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 

.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