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

N
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?
1 of 16

Recommended

.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NET by
.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NET.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NET
.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NETNETFest
705 views74 slides
.NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE... by
.NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE....NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE...
.NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE...NETFest
341 views41 slides
.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NET by
.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NET.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NET
.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NETNETFest
616 views43 slides
.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистов by
.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистов.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистов
.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистовNETFest
516 views40 slides
.NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem... by
.NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem....NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem...
.NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem...NETFest
254 views7 slides
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design by
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven DesignNETFest
1.5K views55 slides

More Related Content

More from NETFest

.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture by
.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
326 views7 slides
.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests by
.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests
.NET Fest 2019. Анатолий Колесник. Love, Death & F# TestsNETFest
224 views39 slides
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос... by
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос....NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...NETFest
275 views20 slides
.NET Fest 2019. Roberto Freato. Azure App Service deep dive by
.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
197 views19 slides
.NET Fest 2019. Леонид Молотиевский. DotNet Core in production by
.NET Fest 2019. Леонид Молотиевский. DotNet Core in production.NET Fest 2019. Леонид Молотиевский. DotNet Core in production
.NET Fest 2019. Леонид Молотиевский. DotNet Core in productionNETFest
250 views31 slides
.NET Fest 2019. Александр Демчук. How to measure relationships within the Com... by
.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
204 views42 slides

More from NETFest(20)

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

Recently uploaded

11.28.23 Social Capital and Social Exclusion.pptx by
11.28.23 Social Capital and Social Exclusion.pptx11.28.23 Social Capital and Social Exclusion.pptx
11.28.23 Social Capital and Social Exclusion.pptxmary850239
281 views25 slides
ACTIVITY BOOK key water sports.pptx by
ACTIVITY BOOK key water sports.pptxACTIVITY BOOK key water sports.pptx
ACTIVITY BOOK key water sports.pptxMar Caston Palacio
430 views4 slides
AUDIENCE - BANDURA.pptx by
AUDIENCE - BANDURA.pptxAUDIENCE - BANDURA.pptx
AUDIENCE - BANDURA.pptxiammrhaywood
69 views44 slides
Narration ppt.pptx by
Narration  ppt.pptxNarration  ppt.pptx
Narration ppt.pptxTARIQ KHAN
119 views24 slides
Create a Structure in VBNet.pptx by
Create a Structure in VBNet.pptxCreate a Structure in VBNet.pptx
Create a Structure in VBNet.pptxBreach_P
70 views8 slides
231112 (WR) v1 ChatGPT OEB 2023.pdf by
231112 (WR) v1  ChatGPT OEB 2023.pdf231112 (WR) v1  ChatGPT OEB 2023.pdf
231112 (WR) v1 ChatGPT OEB 2023.pdfWilfredRubens.com
144 views21 slides

Recently uploaded(20)

11.28.23 Social Capital and Social Exclusion.pptx by mary850239
11.28.23 Social Capital and Social Exclusion.pptx11.28.23 Social Capital and Social Exclusion.pptx
11.28.23 Social Capital and Social Exclusion.pptx
mary850239281 views
AUDIENCE - BANDURA.pptx by iammrhaywood
AUDIENCE - BANDURA.pptxAUDIENCE - BANDURA.pptx
AUDIENCE - BANDURA.pptx
iammrhaywood69 views
Narration ppt.pptx by TARIQ KHAN
Narration  ppt.pptxNarration  ppt.pptx
Narration ppt.pptx
TARIQ KHAN119 views
Create a Structure in VBNet.pptx by Breach_P
Create a Structure in VBNet.pptxCreate a Structure in VBNet.pptx
Create a Structure in VBNet.pptx
Breach_P70 views
Class 10 English notes 23-24.pptx by TARIQ KHAN
Class 10 English notes 23-24.pptxClass 10 English notes 23-24.pptx
Class 10 English notes 23-24.pptx
TARIQ KHAN107 views
Structure and Functions of Cell.pdf by Nithya Murugan
Structure and Functions of Cell.pdfStructure and Functions of Cell.pdf
Structure and Functions of Cell.pdf
Nithya Murugan368 views
Psychology KS4 by WestHatch
Psychology KS4Psychology KS4
Psychology KS4
WestHatch68 views
JiscOAWeek_LAIR_slides_October2023.pptx by Jisc
JiscOAWeek_LAIR_slides_October2023.pptxJiscOAWeek_LAIR_slides_October2023.pptx
JiscOAWeek_LAIR_slides_October2023.pptx
Jisc79 views
OEB 2023 Co-learning To Speed Up AI Implementation in Courses.pptx by Inge de Waard
OEB 2023 Co-learning To Speed Up AI Implementation in Courses.pptxOEB 2023 Co-learning To Speed Up AI Implementation in Courses.pptx
OEB 2023 Co-learning To Speed Up AI Implementation in Courses.pptx
Inge de Waard167 views
The basics - information, data, technology and systems.pdf by JonathanCovena1
The basics - information, data, technology and systems.pdfThe basics - information, data, technology and systems.pdf
The basics - information, data, technology and systems.pdf
JonathanCovena188 views
Are we onboard yet University of Sussex.pptx by Jisc
Are we onboard yet University of Sussex.pptxAre we onboard yet University of Sussex.pptx
Are we onboard yet University of Sussex.pptx
Jisc77 views
American Psychological Association 7th Edition.pptx by SamiullahAfridi4
American Psychological Association  7th Edition.pptxAmerican Psychological Association  7th Edition.pptx
American Psychological Association 7th Edition.pptx
SamiullahAfridi482 views
Drama KS5 Breakdown by WestHatch
Drama KS5 BreakdownDrama KS5 Breakdown
Drama KS5 Breakdown
WestHatch71 views

.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